编程知识 cdmana.com

Java design pattern Factory Method Pattern

A detailed explanation of the factory method model

   Today we mainly study Java Factory method pattern in design pattern , If you have read the simple factory model I wrote before, it will be easier to understand the following explanation , I still use the case method in food processing plant to understand .

One , summary

   The factory method pattern removes the static properties of factory methods in the simple factory pattern , So that it can be inherited by subclasses . In this way, in the simple factory mode, the pressure on the factory method can be different from that in the factory method mode    To share .

   The factory method pattern uses multiple subclasses inherited from the abstract factory role to replace the... In the simple factory pattern “ Top class ”. This shares the burden of creating objects ; Avoid using logical judgment in factory classes to decide to create objects ,   And it makes the structure quite flexible when there are new products , Just follow the abstract product role 、 Abstract rules provided by factory roles to generate , Then it can be used by customers , You don't have to modify anything you already have    Code , It can be seen that the plant method mode conforms to the open close principle .

Two , Structure diagram

  • AbstractProduct Class : Abstract product class , The superclass of all objects created by the factory method pattern , It is responsible for describing the common interface shared by all instances
  • Berr Class sum Drinks Class : Specific product categories , It's the goal of a simple factory model
  • AbstractFactory Class : Abstract factory class , This is the core of the factory approach model , It is the interface that a specific factory role must implement or the parent class that it must inherit . stay java It is implemented by abstract classes or interfaces
  • BerrFactory Class sum DrinksFactory Class : Specific factory class , It contains code related to specific business logic . Called by the application to create the corresponding product specific object

  3、 ... and , Examples

   Let's take food processing plants as an example , Suppose there's a food processing plant , It mainly processes beer and mineral water , On demand , We need a separate class to specialize in the production of beer drinks, mineral water , Because of me    Our factory will be bigger and stronger in the later period , So we have to consider the impact of this design on the subsequent business development , Our factory requires that at the beginning of the design, it must be on the basis of not affecting the existing business , Flexible to expand new systems    Manufacturing business , According to the needs of food processing plants , We used the factory approach design pattern .

  Four , Specific code implementation

   First step : Designing our products is what we want to produce , According to the structure, we design the code as follows

   Abstract product class code is the parent of all products , The code is as follows :

package pattern.factory.product;/** *  Creating product abstract classes can also be defined by interfaces  * @author ningbeibei * */public abstract class AbstractProduct {    // Get the product abstract method , You need a specific implementation class to implement     public abstract void getFood();}

   Specific products Berr( beer ), The code is as follows :

package pattern.factory.product;/** *  Beer specific beer classes are inherited from AbstractProduct Class  * @author ningbeibei */public class Berr extends AbstractProduct {    @Override    public void getFood() {        System.out.println(" beer ");    };}

   Specific products Drinks ( Drinks ), The code is as follows :

package pattern.factory.product;/** *  The concrete beverage class inherits from AbstractProduct * @author ningbeibei */public class Drinks extends AbstractProduct {    @Override    public void getFood() {        System.out.println(" Drinks ");    }}

   The second step : Factories that design and manufacture products , This is also the most important part of the factory method model

   Create factory abstract class , The code is as follows :

package pattern.factory.factorymill;import pattern.factory.product.AbstractProduct;/** *  Abstract factory class , Food processing plants need abstract design  * @author ningbeibei * */public abstract class AbstractFactory {    // This abstract method returns a product object ,    public abstract AbstractProduct createProduct(); }

   Establish specific brewery class BerrFactory, The code is as follows :

package pattern.factory.factorymill;import pattern.factory.product.AbstractProduct;import pattern.factory.product.Berr;/** *  Factories that know beer , This class is implemented from  AbstractFactory Abstract class  *  Returns a beer product object  * @author ningbeibei * */public class BerrFactory extends AbstractFactory {        // Implement abstract factory to return beer     @Override    public AbstractProduct createProduct() {        return new Berr();    }}

   Establish a specific beverage manufacturing factory , The code is as follows :

package pattern.factory.factorymill;import pattern.factory.product.AbstractProduct;import pattern.factory.product.Drinks;/** *  It's a beverage factory , Inherited from AbstractFactory Abstract class  * @author ningbeibei */public class DrinksFactory extends AbstractFactory {    // Return to beverage items     @Override    public AbstractProduct createProduct() {        return new Drinks();    }}

   The third step : Write test class for test verification

 

package pattern.factory;import pattern.factory.factorymill.BerrFactory;import pattern.factory.factorymill.DrinksFactory;import pattern.factory.product.AbstractProduct;/** *  Factory method pattern test class  * @author ningbeibei */public class test {    public static void main(String[] args) {        // Start with a brewery         BerrFactory berrfactory = new BerrFactory();        // Call the brewery createProduct() Method , Create beer object and return         AbstractProduct product = berrfactory.createProduct();        // Export beer         product.getFood();                // Start with a beverage factory         DrinksFactory drinksfactory = new DrinksFactory();        // Call in the beverage factory createProduct() Method , Create a drink object and return         AbstractProduct drinksproduct = drinksfactory.createProduct();        // Export drinks         drinksproduct.getFood();    }}

 

   Test results :

5、 ... and , How to expand a suite of new products

   With the expansion of food processing scale , Our food processing plants want to make more products , Now I want to make mineral water , According to the idea at the beginning of the design , No matter what kind of later business expansion kit products will not shake the existing code , That is, it does not violate the opening and closing principle of the factory mode .

  1. Add new product mineral water class and inherit abstract product class , The code is as follows :

package pattern.factory.product;/** *  New mineral water products , Also inherited from product abstract classes AbstractProduct * @author ningbeibei * */public class Water extends AbstractProduct {    @Override    public void getFood() {        System.out.println(" Mineral water ");    }}

  2. Add concrete manufacturing mineral water factory class and inherit abstract class AbstractFactory, The code is as follows :

 

package pattern.factory.factorymill;import pattern.factory.product.AbstractProduct;import pattern.factory.product.Water;/** *  New mineral water factories  *  Inherited from AbstractFactory Abstract class  * @author ningbeibei * */public class WaterFactory extends AbstractFactory{    // Make mineral water objects and return to     @Override    public AbstractProduct createProduct() {        return new Water();    }}

 

  3. Test class writing , The code is as follows :

package pattern.factory;import pattern.factory.factorymill.BerrFactory;import pattern.factory.factorymill.DrinksFactory;import pattern.factory.factorymill.WaterFactory;import pattern.factory.product.AbstractProduct;/** *  Factory method pattern test class  * @author ningbeibei */public class test {    public static void main(String[] args) {        // Start with a brewery         BerrFactory berrfactory = new BerrFactory();        // Call the brewery createProduct() Method , Create beer object and return         AbstractProduct product = berrfactory.createProduct();        // Export beer         product.getFood();                // Start with a beverage factory         DrinksFactory drinksfactory = new DrinksFactory();        // Call in the beverage factory createProduct() Method , Create a drink object and return         AbstractProduct drinksproduct = drinksfactory.createProduct();        // Export drinks         drinksproduct.getFood();                // This is a new product mineral water         WaterFactory waterfactory = new WaterFactory();        // Call mineral water factory createProduct() Method , Create mineral water objects and return         AbstractProduct waterproduct = waterfactory.createProduct();        // Export mineral water         waterproduct.getFood();    }}

  4. Test results :

 

 

  6、 ... and , Advantages and disadvantages of the factory method model

   Disadvantages :

  • It's easy to have too many classes , Increase complexity
  • It increases the abstraction and understanding difficulty of the system
  • Abstract products can only produce one product , This problem can be solved by using abstract factory pattern   

  Advantages :

  • Users only need to know the name of the specific factory to get the products they want , There is no need to know the specific process of product establishment
  • Increased flexibility , For the establishment of new products , Just write one more factory class
  • A typical decoupling framework . High level modules only need to know the abstract class of the product , Don't worry about other implementation classes , Meet the Demeter's law 、 The principle of Dependence Inversion and the principle of Richter's substitution

 

7、 ... and , Learning ideas

   Start with a simple factory model ===》 And then the factory method model ====》 Finally, the abstract factory pattern

   From the shallow to the deep learning in order to understand the deeper and more comprehensive, and then can be integrated

   I hope the criticism can correct the shortcomings of the writing , I will change it

&n

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225152058063m.html

Scroll to Top