factory pattern
Creation Mode:
Abstracting the instantiation process of a class can separate the creation of objects from the use of objects
- In order to make the structure of the software clearer, the outside world only needs to know the common interface for these objects, and does not care about the details of the specific implementation, which makes the whole system more in line with the principle of single responsibility
- The creational pattern hides the creation details of the instance of the class, and makes the whole system independent of each other by hiding the object creation and composition process.
- Creativity patterns are more flexible in what, by whom, and when
- The factory pattern is an important creational pattern whose main function is to instantiate objects
factory pattern: is responsible for instantiating classes with a common interface
- mainly solves the problem of interface selection
- Use when you need to create different instances under different conditions
- Factory pattern is a creational pattern that provides the best way to create objects
- Creating objects using the factory pattern does not expose creation logic to clients, and uses a common interface to point to newly created objects
- The factory pattern implements the factory interface in the subclass, and the creation process is performed in the subclass
Classification of factory patterns:
- Simple Factory Pattern Simple Factory
- Factory Method Pattern Factory Method
- Abstract Factory Pattern Abstract Factory
Factory Mode Advantages:
- It can make the code structure clear and effectively encapsulate changes
- Block specific product categories from callers
- Reduce code coupling
Factory mode usage scenarios:
- Wherever complex objects need to be generated, the factory method pattern can be used. Only complex objects are suitable for the factory method pattern. For simple objects that can be created by new , there is no need to use the factory pattern. If simple objects Using the factory pattern, you need to introduce a factory class to increase the complexity of the system
- The factory pattern is a typical decoupling pattern. When dependencies between classes need to be increased, the factory pattern can be used to reduce the coupling between systems
- The factory pattern relies on the abstract architecture, and the task of instantiation is handed over to the subclass for implementation, which has good scalability. When the system needs better scalability, the factory pattern can be used, and different products use different factories to achieve assembly
Simple Factory Pattern
Simple Factory Pattern:
- Define a class to be responsible for creating instances of other classes, and return instances of different classes according to different arguments. The created instances usually have a common parent class
- The method used to create an instance in the simple factory pattern is a static static method, so it is also called a static factory method pattern
The role of the simple factory pattern:
- Factory class Factory : Simple factory pattern core class. Responsible for creating the internal logic of all products, the factory class can be called externally to create the required objects
- The abstract product class Product : The parent class of all objects created by the factory class, encapsulates the common methods of the product. It improves the flexibility of the system. The factory class only needs to define a common factory method, because all the specific products created are this subclass object
- Concrete product class ConcorrectProduct: All created objects are concrete instances of this class and need to implement the abstract methods declared in the abstract product
- Simple Factory Pattern Code Implementation
simple factory pattern:
- The simple factory pattern provides a special class for creating objects and realizes the division of responsibilities. The factory class Factory contains the necessary judgment logic to decide to create an instance of the concrete product class ConcreteProduct , and the client only needs to consume the product
- The client does not need to know the class name of the specific product class ConcreteProduct to be created, but only needs to know the parameters corresponding to the specific product class ConcreteProduct
- By introducing configuration files, new product classes can be modified and added without modifying the client. ConcreteProduct, Improve the flexibility of the system
Simple Factory Pattern Disadvantages:
- Factory class Factory centralizes the creation logic of all products, if an exception occurs, the entire system will fail
- The number of classes in the system is increased in the simple factory pattern, which increases the complexity and difficulty of understanding the system
- In the simple factory mode, if you need to add new products, you need to modify the factory logic, which violates the open-closed principle and is not conducive to the expansion and maintenance of the system.
- The simple factory pattern uses static methods and cannot form a hierarchical structure based on inheritance
Simple factory pattern usage scenario:
- When there are few objects in the factory class responsible for creating
- The client only needs to know the parameters passed to the factory class, and does not care about the parameters of the object created
Simple factory class implementation
Directly pass in the judgment parameter key
Factory:
public class Factory { public static Product produce(String concreteProductType) { switch (concreteProductType) { case "A" : return new ConcreteProductA(); break; case "B" : return new ConcreteProductB(); break; default : throw new Exception("没有对应的产品类型"); break; } } }
Issue:
- If you add a new product category, you need to add case to the factory category
- Violating the open-closed principle, this method is not recommended
use reflection
- Factory:
public Class Factory {
public static Product produce(String concreteProductClassPathName) throw Exception {
try {
Product product = (Product)Class.forName(concreteProductClassPathName).newInstance();
return product;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
throw new Exception("没有对应的产品");
}
}
Question:
- If you add a new product class, you need to pass in the classpath name of the specific product class
- It can be optimized through the configuration file, configure the classpath name of the specific product class in the properties file, and pass the classpath name into the method of the factory class by loading the configuration file
- In this way, to add product categories, you only need to modify the configuration file.
Combining reflection and configuration files
product.properties:
A=com.oxford.factory.simple.ConcreteProductA B= com.oxford.factory.simple.ConcreteProductB
PropertyReader: adds a configuration file reading class to read the configuration file information into Map
public Class PropertyReader { public static Map<String, String> property = new HashMap<>(); public Map<String, String> readProperty(String fileName) { Properties properties = new Properties(); InputStream input = getClass.getResourceAsStream(fileName); try { pro.load(input); Iterator<String> iterator = pro.StringPropertyNames().iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = properties.getProperty(key); map.put(key, value); } input.close(); } catch (IOException e) { e.printStacTrace(); } return map; } }
Factory:
public Class Factory { public static Product produce(String concreteProductType) throws Exception { PropertyReader reader = new PropertyReder(); Map<String, String> property = reader.readProperty("property.properties"); try { Product product = (Product)Class.forName(property.get(concreteProductType)).newInstance(); return product; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } throw new Exception("没有对应的产品"); } }
Issue:
- Each time the method is called, the configuration file must be parsed, increasing the system overhead
- The file reading class can be loaded when the program starts, so you don't have to parse the configuration file every time it is called
Simple Factory Pattern Summary
factory class is the key to the whole simple factory pattern:
- The factory class contains the necessary judgment logic to decide which specific product class to create according to the given parameters
- By using the factory class, the client only needs to consume the specific product without paying attention to the creation process of the specific product object
- By using the simple factory pattern, the responsibilities of each class are clarified, which is beneficial to the optimization of the entire software architecture
- The factory class concentrates the creation logic of all specific objects, which violates the principle of high cohesion of responsibility distribution. In this way, the classes created in the factory class can only be considered in advance. If you need to add new classes, you need to modify the factory class. logic, which violates the open-closed principle
- When the number of specific product types in the system continues to increase, there will be a need for the factory class to create different instances according to different conditions. This kind of judgment on conditions and judgment on specific product types are intertwined, which is not conducive to the system. Extension and maintenance. Such problems can be optimized by using the factory method pattern
Factory Method Pattern
Method Pattern:
- Define an interface for creating objects, and decide to instantiate a specific class by implementing the class of this interface
- Factory method pattern delays instantiation of concrete classes to subclasses
The role of the factory method pattern:
Factory class Factory:
- Factory method interface, which usually returns an instance object of the abstract product type Product
- This class is the core of the factory method pattern and has nothing to do with client programs. Any concrete product created in the pattern needs to implement this interface
Factory implementation class ConcreteFactory:
- Factory class interface implementation, overwrite the factory method defined by Factory Factory , and return an instance of the abstract product type Product of the concrete product class ConcreteProduct
- The factory implementation class ConcreteFactory contains logic closely related to the client and is called by the client to create a concrete product instance
Abstract Product Class Product:
- The parent class of the specific product class created by the factory method pattern, which defines the methods common to the specific product of the class
Concrete Product: ConcreteProduct:
- The concrete product implementation class implements the methods in the abstract product class Product
- Each object created by the factory pattern is an instance of the concrete product class ConcreteProduct
- Factory Method Pattern Code Implementation
Factory Method Pattern Advantages:
- In the Factory Method pattern, the client needs to create products through factory methods ConcreteProduct, users only need to be concerned about the need for specific products ConcreteProduct corresponding factory implementation ConcreteFactory. do not care about the specific product ConcreteProduct create and details Name of ConcreteProduct ConcreteProduct
- Based on factory class Factory's and abstract product class Product polymorphism design is the key factory method pattern. Such factory class Factory's can independently determine what products you need to create ConcreteProduct objects, and create specific products The concrete implementation of the ConcreteProduct object is encapsulated inside the concrete factory ConcreteFactory . The concrete factory class ConcreteFactory all have the same parent class interface Factory, so
- The factory method pattern fully complies with the open-closed principle, which is conducive to the expansion and maintenance of the system. When adding a new product to the system, the factory method pattern only needs to add a concrete factory class ConcreteFactory and a concrete product class ConcreteProduct
Factory Method Pattern Disadvantages:
- When adding a new product to the system in the factory mode, it is necessary to add the specific product class ConcreteProduct and the specific factory class ConcreteFactory, The number of classes in the system increases in pairs, which increases the complexity of the system and the overhead of system compilation and operation to a certain extent
Usage scenarios of factory method pattern:
- A class does not need to know the class of the object it needs: the factory method pattern, the client does not know the class name of the specific product class, but only knows which specific factory implements the specific product object to create. At this time, the client Need to know the specific factory implementation class that creates the specific product
- A class specifies which object to create by subclassing: factory method pattern, only one interface for creating a product is required in the factory class, and the subclass determines the specific object to be created. By using polymorphism and Richter code According to the principle of replacement, when the program is running, the parent class object can be overwritten by the subclass object, so that the system can be extended
- By handing over the task of creating specific products to the specific factory implementation of the factory class, the client does not need to care about the creation of specific product classes, and can dynamically specify the specific factory implementation of the product when needed. The class name of the specific factory class can be Stored in a configuration file or database
Examples of usage scenarios for the factory method pattern:
- Logger: log can record to local disk, system events, remote server, etc., user can choose the location of logging
- access: the user does not know which type of database the system uses in the end, and when the database may change
- Server framework design: designing a framework for connecting to a server, three protocols, POP3, IMAP, and HTTP, may be used. The three protocols can be regarded as specific product classes and implemented using the factory method pattern.
Factory Method Pattern Summary
- The factory method pattern is an abstraction and extension of the simple factory pattern. Through polymorphism, the factory method pattern maintains the advantages of the simple factory pattern and improves the shortcomings of the simple factory pattern.
- In the factory method pattern, the core factory class only gives the interfaces that the specific factory implementation must implement, and is no longer responsible for the creation of specific products. The creation of specific products is completed by the specific factory implementation. This allows the system to implement without modifying the core factory. The extension of the specific product implementation when the class is implemented
Advantages:
- If the client wants to create an object, it only needs to know the specific factory implementation.
- The scalability of the system is high. If you add a new product, you only need a specific factory implementation class and a specific product class, which conforms to the open-closed principle.
- The specific implementation is hidden from the client, and the client only needs to care about the specific factory implementation.
:
- Every time you add a product, you need to add a specific factory implementation class and a specific product class, which doubles the number of classes in the system, increases the complexity of the system to a certain extent, and increases the dependency of specific classes in the system. , and the addition of classes also increases the system overhead of compilation and runtime
Abstract Factory Pattern
Abstract Factory Pattern:
- Provides an interface or abstract class for creating a set of related or interdependent concrete product objects without specifying a specific class
The basic idea of abstract factory pattern:
- The factory method pattern solves the problem of excessive responsibilities of the factory class in the simple factory pattern by introducing the factory hierarchy. However, since each factory in the factory method pattern only produces one type of product, this may lead to the problem of a large number of factory classes , which will increase the cost of the system
can group some related products into a product family, and the same factory can produce
- Product Family: A family of functionally related products located in different product hierarchy
difference between abstract factory pattern and factory method pattern:
Abstract Factory Pattern:
- The abstract factory pattern is a hierarchical structure for multiple products
- The concrete product of the abstract factory pattern implements or inherits from different interfaces or abstract classes
Factory Method Pattern:
- The Factory Method pattern is a hierarchical structure for a product
- The concrete product of the factory method pattern implements or inherits from the same interface or abstract class
The role of the abstract factory pattern:
- Abstract factory class AbstractFactory: The core of the abstract factory pattern, which has nothing to do with the business logic of the application. It is usually implemented using an interface or an abstract class. All concrete factory classes ConcreteFactory must implement an interface or an abstract class
- Concrete factory class ConcreteFactory: Implement the methods defined by the factory, including the business logic for creating concrete product instances
- AbstractProduct: defines the interface or abstract class of a class of product objects, which is the parent class of objects created by the factory method pattern
- ConcreteProduct: A concrete product that implements business logic. Each product object created in the abstract factory is an instance of a concrete product
- Abstract Factory Pattern Code Implementation
Abstract Factory Pattern Advantages:
- The abstract factory pattern separates the generation of concrete classes, and the client does not need to know the concretely created classes
- When objects in a product family are designed to work together, clients can be guaranteed to only use objects from the same product family
Abstract Factory Pattern Disadvantages:
- Difficulty extending the product hierarchy if new product objects are added
Usage scenarios of abstract factory pattern:
- The details of the creation, composition, and presentation of a system that does not depend on concrete instances of product classes
- There are multiple product families in the system, and only one of them is used at a time
- Products from the same product family are used together
- The system provides a product library, the client does not depend on the implementation of specific products, and all products appear with the same interface
- The system structure is stable, and the product family will not be added frequently
abstract factory pattern problem: The inclination of the open-closed principle
- The inclination of the open-closed principle in the abstract factory pattern means that in the abstract factory pattern, it is convenient to add new products, but it is very troublesome to add new product families
The open-closed principle requires that the system is closed for modification and open for extension. Functional expansion enhancements for systems with multiple product families and multiple product hierarchy structures include:
- Add products: For adding new products, you only need to add a corresponding specific factory, no need to modify the existing code
Add product family: For the product hierarchy structure of adding a new product family, it is necessary to modify all factory roles, including abstract factory classes, and in all factory classes, it is necessary to add methods to produce new product family products, which is contrary to open-closed principle
- Because the abstract factory pattern has the inclination of the open-closed principle, it is required to consider all product families of the entire system at the beginning of the system design, and will not add new product families or delete existing products after the design is completed. Family. Otherwise, it will lead to a large number of changes in the system, which is difficult to maintain
Abstract Factory Pattern Summary
- The abstract factory pattern is a further extension of the factory method pattern, providing a more powerful factory class for system expansion
- The abstract factory pattern separates the generation of concrete classes, and the client does not need to know the product creation process, which makes it easy to switch concrete factories. Because all concrete factories implement the public interface defined in the abstract factory, only the concrete factory needs to be changed. instance, you can change the behavior of the entire system
- When multiple product objects in a product family work together, it is guaranteed that clients always use only objects from the same product family
- It is very convenient to add new products, without modifying the existing system, in line with the principle of opening and closing
- However, it is very troublesome to increase the product hierarchy of the new product family of the system. It requires a lot of modifications to the original system, and even the code of the abstract layer needs to be modified, which violates the open-closed principle.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。