To put it simply, the factory pattern helps us create objects, hides the complexity of the object creation process (for example, class B needs to call class A, the factory class provides the creation interface of class A, B only needs to call the interface to pass in the corresponding parameters), and saves you from the hard work of preparing constructor parameters. In plain English, factories provide products to customers. (There are three types of factories according to the way of providing products: simple factories, factories and abstract factories.)

Factory mode is the most commonly used instantiation object mode, which uses factory methods instead of new operations. The well-known Jive forum makes extensive use of the factory pattern, which can be seen everywhere in Java programming systems. Because factory mode is the equivalent of creating new instance objects, we often need to generate instance objects based on the Class, such as A A =new A() factory mode is also used to create instance objects, so we need to be careful about whether to use factory mode when new, although it may require A little more work. But it will give you more scalability and less modification

role

The factory pattern has the following roles (as understood in the following flowchart), and the product is the instance object that needs to be created

  • Abstract product class: A parent class of the created product that gives an abstract interface or abstract class and is generally implemented by a concrete product class. (expression of polymorphism) — like Animal
  • Concrete product class: An implementation class of an abstract product class, an object that implements a concrete product. – like a Dog
  • Abstract Factory class: The factory provides the method for creating products, the core of the factory method pattern (the simple factory pattern does not have this abstract class), and is application-independent. Is the interface that the concrete factory must implement or the parent class that it must inherit.
  • Concrete factory class: Inherits the abstract factory class to implement concrete business logic.

Factory pattern and Abstract factory pattern

Diagrammatic factory model versus abstract factory model processes

Factory mode:



Abstract Factory pattern:


Simple Factory Pattern (Static Factory approach)

Meaning: There is no abstract factory class, the factory class itself provides the product with the following code

Abstract product classes (Abstract classes or interfaces)

public interface IProduct{

    void method();

}

Copy the code

Concrete product implementation classes

/ / A products

public class ProductA implement IProduct{

    void method(a){

        logger.info("ProductA");

    }

}



/ / B product

public class ProductB implement IProduct{

    void method(a){

        logger.info("ProductB");

    }

}

Copy the code

The factory class

public class Factory{

    // The simple factory pattern has only one static method to provide the product, so it is also called the static factory method

    public static IProduct createProduct(String productName){

        if("A".equals("A") {

            return new ProductA();

        }else if("B".equals("B") {

            return new ProductB();

        }else

    }

}

Copy the code
  • Advantages: Emphasize the single responsibility principle, a class provides only one function
  • Disadvantages: Factory class changes violate the open close principle

The factory pattern

The factory pattern has one abstract factory class for multiple concrete factory implementation classes, one abstract product class for one concrete implementation class, and each concrete factory class can create only one instance of a concrete product class

Abstract product classes (Abstract classes or interfaces)

public interface IProduct{

    void method();

}

Copy the code

Concrete product implementation classes

/ / A products

public class ProductA implement IProduct{

    void method(a){

        logger.info("ProductA");

    }

}



/ / B product

public class ProductB implement IProduct{

    void method(a){

        logger.info("ProductB");

    }

}

Copy the code

Abstract Factory Classes (Abstract classes or interfaces)

public abstract class Factory{    

/ * *

* Abstract factory methods

* What exactly is generated depends on the subclass

*@return Specifies the product object

* /
    

public abstract IProduct createProduct();    

}     

Copy the code

Specific Factory

/ / A factory

public class AFactory extends Factory {

    // Provide A product

    public  IProduct createProduct(a){

        return new ProductA();

     }

}



/ / B factory

public class BFactory extends Factory {

    // Provide product B

    public  IProduct createProduct(a){

        return new ProductB();

     }

}

Copy the code

usage

Factory factory = new AFactory();  

IProduct aProduct = factory.createProduct();  

product.method();  

Copy the code
  • Advantages: It overcomes the disadvantage of simple factory violating the open-closed principle, and retains the advantage of encapsulating the object creation process, reducing the coupling between client and factory, so “factory mode” is the further abstraction and promotion of “simple factory mode”
  • Disadvantages: For each additional product, a sub-plant should be added, increasing the amount of additional development.

Abstract Factory pattern

The factory pattern has one abstract factory class for multiple concrete factory implementation classes, multiple abstract product classes for multiple concrete implementation classes, and each concrete factory class can create instances of multiple concrete product classes.

Abstract product classes (Abstract classes or interfaces)

/ / drink

public interface IDrink{

    void method();

}

/ / food

public interface IFood{

    void method();

}

Copy the code

Concrete product implementation classes

/ / noodles

public class Noddle implement IFood{

    void method(a){

        logger.info("Noodles");

    }

}



/ / rice

public class Rice implement IFood{

    void method(a){

        logger.info("Rice");

    }

}



/ / coke

public class Cola implement IDrink{

    void method(a){

        logger.info("Coke");

    }

}



/ / rice

public class Sprite implement IDrink{

    void method(a){

        logger.info("Sprite");

    }

}

Copy the code

Abstract Factory Classes (Abstract classes or interfaces)

public abstract class Factory{    

/ * *

* Abstract factory methods

* What exactly is generated depends on the subclass

*@return Specifies the product object

* /
    

public abstract IFood createFoodProduct();    

public abstract IDrink createDrinkProduct();    

}     

Copy the code

Specific Factory

//A food factory (provides coke and rice)

public class AFactory extends Factory{

    // Coke is available

    public  IDrink createDrinkProduct(a){

        return new Cola();

     }



     // Rice is served

    public  IFood  createFoodProduct(a){

        return new Rice();

     }   

}



//B food factory (noodles and Sprite)

public class BFactory extends Factory{

    // Noodles are provided

    public  IFood createFoodProduct(a){

        return new Noddle();

     }



 // Sprite is provided

    public  IDrink createDrinkProduct(a){

        return new Sprite();

     }

}

Copy the code

usage

Factory factory = new AFactory();  

IDrink cola = factory.createDrinkProduct();  

cola.method(); 

IFood riceFood = factory.createFoodProduct(); 

riceFood.method();  

Copy the code
  • advantages
    1. It has the advantage of factory method mode decoupling.
    2. The factory pattern addresses one product hierarchy, while the abstract factory pattern addresses multiple product hierarchy. Most importantly, product family relationships can be defined and described within classes.
  • disadvantages
    1. The extension of the product family is laborious, and if a new product needs to be added to the product family, almost all factory classes need to be modified.
    2. In the concrete factory class method, only one of the products in the product family can be used. It’s easy to understand, for example, that a package doesn’t include two drinks (no two air conditioners in the same car).

conclusion

Cut both ways

Advantages: Unified object creation for easy maintenance and overall control, open to extension, closed to modification Disadvantages: Coupling, because the factory class focused all create a logical instance, responsibility allocation principle violated the high cohesion, all create a logical on a factory class, the conditions of judgment, and for the specific product type determine staggered together, it is difficult to avoid the spread of the module function, the system maintenance and extension is very adverse.

Restricted use

As you can see from the example of the factory pattern, the factory pattern requires classes to implement its interfaces and has obvious inheritance relationships within the business, such as the relationship between cars and Mercedes and BMW. Inheritance relationships often exist between models, and it is difficult to have inheritance relationships between businesses, so what if there is no such explicit inheritance relationships within or between businesses? Even if there is an inheritance relationship within the business, you can manage the business in a unified way, which increases the coupling of the code and makes the factory approach complex and disruptive when creating complex logic.

Its open and closed advantages can be easily replaced

The on-off performance of the system can be improved by being highly hierarchical and modularized without having to apply the factory model rigidly.

Pay attention and don’t get lost

The article continues to update every week, you can wechat search “ten minutes to learn programming” the first time to read and urge more, if this article is written well, feel something ~ for praise 👍 for attention ❤️ for share ❤️ everyone’s support and recognition, is the biggest power of my creation, we see the next article!