Original: Curly brace MC(wechat official account: Huakuohao-MC), welcome to share, please keep the source.

Abstract factories provide an interface to create a series of related or interdependent objects without specifying their concrete classes. Simply put, it provides a solution for scenarios where multiple related products need to be created.

For example

Many programs support themes with different colors. When switching themes, all button styles and colors will be switched uniformly.

Suppose our software only has three types of buttons, namely Button, TextField, and ComboBox, and our software only provides two types of themes, namely red theme and green theme.

Take a look at UML:

Let’s see how the code works.

Start by creating a SkinFactory interface

public interface SkinFactory {
    Button createButton();
    TextField createTextField();
    ComboBox createComboBox();
}
Copy the code

Implement a green theme factory by implementing SkinFactory

Public class implements SkinFactory {@override public Button createButton() {return new RedButton(); } @Override public TextField createTextField() { return new RedTextField(); } @Override public ComboBox createComboBox() { return new RedComboBox(); }}Copy the code

The red theme factory class is similar and not listed separately for reasons of space.

How does the client work

Public class Client {public static void main(String[] args){ SkinFactory SkinFactory = new RedSkinFactory(); Button button = skinFactory.createButton(); ComboBox comboBox = skinFactory.createComboBox(); TextField textField = skinFactory.createTextField(); button.display(); comboBox.display(); textField.display(); }}Copy the code

conclusion

Abstract factory is one of creating patterns, the abstract factory over correlated with suitable to create a series of products, while a theme of abstract factory in extension button is agile and convenient, but also has some shortcomings, the biggest weakness is expected to add a alone does not belong to any topic button more troublesome, such as the above example, if you want to add a close button, This button is not a red or green theme, so it is more complicated to change.

The factory pattern has three brothers: simple factory is suitable for scenarios with simple logic and small number of products, factory mode is suitable for creating independent products, and abstract factory is suitable for creating a series of related multiple products.


Recommended reading

1. Java concurrent programming stuff (10) — Final summary

2. Common network problem locating tools that programmers should master

3. Do you know how to use Awk

4. Teach you how to build a set of ELK log search operation and maintenance platform


Original: Curly brace MC(wechat official account: Huakuohao-MC) Focus on JAVA basic programming and big data, focus on experience sharing and personal growth.