I have been learning the design patterns for a long time and want to classify and summarize them, but I don't know where to start. If we find that the factory model is a series, let's start with three factory models.
First, let's take the simple factory mode and take the design calculator as an example to analyze this mode. The simple factory mode abstracts a parent class of the business logic, and the parent class defines the attributes and methods, the suboperation class only needs to override the operation method. The client is responsible for inputting and outputting data, and the operation factory class decides to instantiate the object.
Simple factory structure diagram:
The simple factory separates the business logic from the interface logic. However, if we need to add or reduce the calculator function, we need to modify the operation factory class. This mode is not in line with the open and closed principle and should be used with caution.
The simple factory mode of the front edge solves this problem because the operation factory class does not comply with the open and closed principle. Take the calculator as an example. Based on the simple factory mode, we can improve this mode. We write the selection method of the computing factory into the factory class and then abstract a public interface, this interface is implemented by each sub-factory class to determine which object should be instantiated.
Factory method class structure: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140524/20140524091050107.jpg" alt = "\">
The factory method mode overcomes the disadvantages of a simple factory that violates the open and closed principle, and maintains the advantages of the encapsulated object creation process. Its disadvantage is that each time a product is added, a product factory class needs to be added, and additional development workload is added. The factory method does not avoid the problem of selecting and judging, only the task is handed over to the client.
Abstract Factory mode: provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes. The advantage of the abstract factory is that it is easy to switch the product series and separate the instance creation process from the client.
Abstract Factory class structure:
The abstract factory does not solve the problem of selection judgment. Here we introduce the reflection method to make the selection judgment into variables for processing, that is, to convert the program selection judgment from compile-time to runtime for processing.
In software development, the use of design patterns is a double-edged sword. if used properly, it can help us better solve the problem. If improperly handled, it will make software development and maintenance more difficult.