Before we get into abstract factories we need to understand two concepts:

  • Product hierarchy: The product hierarchy is the inheritance structure of the product. If an abstract class is TV, and its subclasses are Haier TV, Hisense TV and Skyworth TV, a product grade structure is formed between the abstract TV and the TV of the specific brand. Abstract TV is the parent class, while the TV of the specific brand is its subclass.

  • ** Product family: ** In the abstract factory model, product family refers to a group of products produced by a factory located in different product grade structure, such as Haier TV and Haier refrigerator produced by Haier Electric Appliances. Haier TV is located in the TV product grade structure, and Haier refrigerator is located in the refrigerator product grade structure. Haier TV set, Haier refrigerator constitute a product family.

There are four product families in the figure, distributed in three different product level structures. A product can be uniquely identified by specifying the product family it belongs to and the hierarchical structure it belongs to.

Introduce the abstract factory pattern

Abstract factory refers to a factory hierarchy that can create all objects in a product family that belong to different product hierarchies. If described by graph, it is shown as follows:

define

The Abstract Factory pattern provides an interface for creating a series of related or interdependent objects without specifying their concrete classes.

structure

Abstract factories contain the following roles:

  • An abstract factory defines an interface that all concrete factories must implement and contains a set of methods to produce products.
  • ConCreteFactory implementations generate different concrete product families. To create a product, the client primarily uses one of these factories without instantiating any product objects.
  • IProduct: Abstract Products Different abstract products are different product families, each concrete factory can realize a complete set of products
  • ConcreteProduct: Realization of concrete classification of abstract products by concrete products

Sample scenario

Speaking of abstract factory, we have to think of the electronics city in various cities. There’s nothing you can’t think of, nothing they can’t produce. Have you ever bought a $500 Iphone? Have you seen an Android iPhone with a Xiaomi camera? Let’s take a look at how android phones are made in Electronics City. The mobile phone seller, also known as our mobile phone factory, can assemble a mobile phone using the motherboard, camera and phone casing:

public interface IFactory {
    MainBoard createMainBoard();

    CameraLens createCameraLens();

    Case createCase();

}
Copy the code

The unscrupulous seller then assembled three types of phones according to the assembly process

/** * iPhone */ public class AppleFactory implements IFactory {@override public MainBoardcreateMainBoard() {
        return new IosMainBoard();
    }

    @Override
    public CameraLens createCameraLens() {
        return new IosCameraLens();
    }

    @Override
    public Case createCase() {
        returnnew IosCase(); }} /** * assemble Android phones */ public class AndroidFactory implements IFactory {@override public MainBoardcreateMainBoard() {
        return new AndroidMainBoard();
    }

    @Override
    public CameraLens createCameraLens() {
        return new AndroidCameraLens();
    }

    @Override
    public Case createCase() {
        returnnew AndroidCase(); }} /** * public class AndroidAppleFactory implements IFactory {@override public MainBoardcreateMainBoard() {
        return new AndroidMainBoard();
    }

    @Override
    public CameraLens createCameraLens() {
        return new AndroidCameraLens();
    }

    @Override
    public Case createCase() {
        returnnew IosCase(); }}Copy the code

Different accessory products

public class AndroidCameraLens implements CameraLens {
    @Override
    public String getCameraLens() {
        return "Android Camera";
    }
}

public class AndroidCase implements Case {
    @Override
    public String getCase() {
        return "Android Phone Case";
    }
}

public class AndroidMainBoard implements MainBoard {
    @Override
    public String getMainBoard() {
        return "Android Motherboard";
    }
}

public class IosCameraLens implements CameraLens {
    @Override
    public String getCameraLens() {
        return Apple CAM;
    }
}

public class IosCase implements Case {
    @Override
    public String getCase() {
        return "IPhone case";
    }
}

public class IosMainBoard implements MainBoard {
    @Override
    public String getMainBoard() {
        return "IPhone motherboard"; }}Copy the code

Then the customer comes to buy the phone

public class App {
    public static void main(String[] args) {
        IFactory factory = new AppleFactory();
        String mainBoard = factory.createMainBoard().getMainBoard();
        String cameraLens = factory.createCameraLens().getCameraLens();
        String aCase = factory.createCase().getCase();
        System.out.println(String.format("Mobile phone accessories: % S, % S, % S, Price: 12888", mainBoard, cameraLens, aCase)); }}Copy the code

SAO years, the new Apple XRS mobile phone accessories: equipped with Apple motherboard, Apple camera, Apple phone shell, price: 12888, do not want to come to a? It doesn’t matter. I have a new Android:

public class App {
    public static void main(String[] args) {
        IFactory factory = new AndroidFactory();
        String mainBoard = factory.createMainBoard().getMainBoard();
        String cameraLens = factory.createCameraLens().getCameraLens();
        String aCase = factory.createCase().getCase();
        System.out.println(String.format("Mobile phone accessories: % S, % S, % S, Price: 4000", mainBoard, cameraLens, aCase)); }}Copy the code

Mobile phone accessories: equipped with Android motherboard, Android camera, Android phone shell, price: 4000, super cost-effective, as long as 4000, do not consider starting? So, SAO years, you and I meet is predestined relationship, I this new lane a secondhand Apple, cheap out of you, you see how

public class App {
    public static void main(String[] args) {
        IFactory factory = new AndroidAppleFactory();
        String mainBoard = factory.createMainBoard().getMainBoard();
        String cameraLens = factory.createCameraLens().getCameraLens();
        String aCase = factory.createCase().getCase();
        System.out.println(String.format("Mobile phone accessories: % S, % S, % S, Price: 4000", mainBoard, cameraLens, aCase)); }}Copy the code

Phone accessories: Android motherboard, Android camera, Apple phone shell, price: 500 only 500, 95 into the new, how.

Don’t take advantage of small things!

advantages

  • The abstract factory pattern isolates the generation of concrete classes so that customers do not need to know what is being created. Because of this isolation, it is relatively easy to change a specific plant. All concrete factories implement the common interfaces defined in the abstract factory, so simply changing an instance of the concrete factory can change the behavior of the entire software system to some extent. In addition, abstract factory pattern can achieve high cohesion and low coupling design purpose, so abstract factory pattern has been widely used.

  • When multiple objects in a product family are designed to work together, it ensures that clients always use only objects in the same product family. This is a very useful design pattern for software systems that need to determine their behavior based on the current environment.

  • It is convenient to add new specific factories and product families without modifying existing systems, in accordance with the open and closed principle.

disadvantages

  • In object, add new products to extend the abstract factory to produce new kinds of products, all this is because the rules in the role of the abstract factory can be created product collection, new kinds of products to support means extensions to the interface, and this will involve the role of the abstract factory and all its subclasses change, obviously brings great inconvenience.

  • The inclination of the open and close principle (easy to add new factories and product families, troublesome to add new product grade structures).

Application scenarios

  • The abstract factory pattern can be used when the objects to be created are a series of interrelated or interdependent product families.
  • There is more than one product family in the system and only one of them is used at a time.
  • Products belonging to the same product family will be used together, and this constraint must be reflected in the design of the system.
  • The system provides a library of product classes, all of which appear in the same interface, so that the client is implementation-independent.

To put it simply, in an inheritance system, if there are multiple hierarchies (that is, there are multiple abstract classes), and there are certain associations or constraints among the implementation classes belonging to each hierarchy, the abstract factory pattern can be used. If there are no relationships or constraints between implementation classes in the hierarchy, it is more appropriate to create products using separate factories.

The inclination of “open close principle”

  • The “open closed principle” requires the system to be open to extension, closed to modification, through extension to enhance its function. For systems involving multiple product families and multiple product hierarchies, enhancements include two aspects:

    1. Add product family: For adding new product family, the factory method pattern well supports the “open closed principle”, for the new product family, only need to add a new specific factory, there is no need to make any changes to the existing code.

    2. Adding a new product hierarchy: To add a new product hierarchy, all factory roles need to be modified, including the abstract factory class, in which methods for producing new products need to be added, and the “open closed principle” is not well supported.

  • This property of the abstract factory pattern is called the slant of the “open closed principle”. The abstract factory pattern supports the addition of new products in a slant way, which facilitates the addition of new product families, but does not provide such convenience for the addition of new product hierarchies.

Degradation of the factory pattern

  • When only one product object is created for each concrete factory class in the abstract factory pattern, that is, only one product hierarchy exists, the abstract factory pattern degenerates into the factory method pattern. The factory method pattern degenerates into a simple factory pattern when abstract factories are merged with concrete factories in the factory method pattern, providing a unified factory to create product objects, and designing the factory method for creating objects as a static method.

conclusion

  • Product hierarchy is the relationship of product inheritance structure. A product family is a group of products produced by a communist and located in a different product hierarchy.

  • The abstract factory pattern provides an interface to create a series of related or interdependent objects without specifying their concrete classes. The Abstract factory pattern, also known as the Kit pattern, belongs to the object creation pattern.

  • Abstract factory consists of four roles: Abstract factory, concrete factory, abstract product and concrete product.

  • Abstract factory pattern is the most abstract and general form of all factory patterns. The main difference between the abstract factory pattern and the factory method pattern is that the factory method pattern targets one product level structure, while the abstract factory pattern needs to face multiple product level structures. It is common practice to implement production methods using factory methods in abstract factories.

  • The main advantage of the abstract factory pattern is that it isolates the generation of concrete classes, so that customers do not need to know what is being created, and multiple objects in a product family can be created from concrete factory classes at a time. It is convenient to add or replace product families, and it is convenient to add new concrete factories and product families. The main disadvantage is the complexity of adding a new product hierarchy, which requires modification of abstract factories and all concrete factory classes, and skewed support for the “open closed principle”.

  • The abstract factory pattern applies where a system should not depend on the details of how product class instances are created, composed, and expressed; There is more than one product family in the system and only one product family is used at a time; Products belonging to the same product family will be used together; The system provides a library of product classes, all of which appear in the same interface, so that the client is implementation-independent.