Simple factory, factory method and abstract factory are three great sisters in the family. Let's introduce the three sisters respectively.
1. Simple factory Definition
The simple factory mode is determined by a factory object to create a product instance. The simple factory model is the simplest and Practical Model in the factory model family. It can be understood as a special implementation of different factory models.
Structure chart
Mode implementation
public class OperationFactory { public static Operation createOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case"-": oper = new OperationSub(); break; case "*": oper=new OperationMul(); break; case"/": oper=new OperationDiv(); break; } return oper; }
Client code:
Operation oper; oper = OperationFactory.createOperate("+"); oper.NumberA = 1; oper.NumberB = 2; double result = oper.GetResult();
In this way, if you want to add complex operations, you must not only add sub-classes, but also modify the operation class factory. Because the open-closed principle is open to expansion and the modification is closed, this violates the Open-expansion principle. So the simple factory was eliminated. Because a simple factory is easy to violate the High Cohesion responsibility allocation principle, it can only be applied in simple cases.
So dajie Abstract Factory and second sister factory are all dedicated to participate in the competition.
Ii. Abstract Factory Definition
Provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
Structure chart
Advantages and disadvantages of Abstract Factory
Advantages
First, it is easy to switch the product series. Because of the specific factory class, it only needs to appear once during initialization in an application. This means it is very easy to change the specific factory of an application, he only needs to change the specific factory to use different product configurations.
Second, it separates the process of creating an instance from the client. The client operates the instance through their abstract interface, and the specific class name of the product is also separated by the implementation of the specific factory, does not appear in the Customer Code.
Disadvantages
Adding a function and adding multiple sub-classes will make the abstract factory very bloated and need to be declared at the beginning of each class. This is a waste of changes.
Abstract Factory structure chart using simple factory Transformation
Implementation
Class dataaccess {Private Static readonly string DB = "sqlserver"; // Private Static readonly string DB = "access"; the database name can be replaced with access public static iuser createuser () {iuser result = NULL; Switch (db) {Case "sqlserver": Result = new sqlserveruser (); break; Case "access": Result = new accessuser (); break ;} return result;} public static idepartment createdepartment () {idepartment result = NULL; Switch (db) // because dB is set in advance, the corresponding object {Case "sqlserver": Result = new sqlserverdepartment (); break; Case "access": Result = new accessdepartment (); break;} can be created based on the selected instance ;} return result ;}}
Client code
static void Main(string[] args) { User user = new User(); Department dept = new Department(); IUser iu = DataAccess.CreateUser(); iu.Insert(user); iu.GetUser(1); IDepartment id = DataAccess.CreateDepartment(); id.Insert(dept); id.GetDepartment(1); Console.Read(); }
The client does not contain any SQL Server or access words, which achieves the goal of decoupling.
The dataaccess class replaces the three factory classes. Because dB values (sqlserver or access) are set, you do not need to enter parameters for simple factory methods, in this way, only dataaccess is required on the client. createuser () and dataaccess. createdepartment.
Use reflection + configuration files to implement data access programs
All the places used in a simple factory can be considered to use the reflection technology to remove the switch or if, to remove the coupling caused by Branch judgment. Reflection technology can solve the problems they cannot cope with, and it is difficult to maintain and expand.
Operation
Add an app. config file with the following content:
<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <appsettings> <add key = "DB" value = "sqlserver"/> // configuration file, which can be replaced by access </appsettings> </configuration>
Add reference system. configruation, add using system. deleettings at the beginning of the program, and change the value assignment code of the dataaccess field dB.
Private static readonly string db=ConfigurationManager.AppSettings["DB"];
Summary
Abstract Factory mode: Multiple abstract product classes. Each abstract product class can be derived from multiple specific product classes. One abstract factory class can be derived from multiple specific factory classes; you can create multiple product instances for each specific factory class.
Iii. Factory method model
The factory method model can be understood as a simple example, that is, Lei Feng is still in the human world.
Definition
The factory method mode defines an interface for creating objects, so that the subclass decides which class to instantiate. The factory method delays the instantiation of a class to its subclass.
Structure chart
Implementation
For example, the implementation of the following structure chart
You can use the factory class to implement the operation class, and the corresponding sub-class factory to implement the sub-operation class. You can use the factory class to instantiate the corresponding operation class.
(1) first build an Interface
interface IFactory { Operation CreateOperation(); }
(2) Use a specific factory to implement this interface
class AddFactory:IFactory { public Operation CreateOperation() { return new OperationAdd(); } } class SubFactory:IFactory { public Operation CreateOperation() { return new OperationSub(); } } class DivFactory:IFactory { public Operation CreateOperation() { return new OperationDiv(); } class MulFactory:IFactory { public Operation CreateOperation() { return new OperationMul(); } }
Client implementation
IFactory operFactory = new AddFactory(); Operation oper = operFactory.CreateOperation(); oper.NumberA = 1 ; oper.NumberB = 2; double result = oper.GetResult();
Summary
The factory method mode is an abstract product class that can be derived from multiple specific product classes. An abstract factory class can be derived from multiple specific factory classes; each factory class can only create one instance of a specific product class.
Iv. Comparison
Simple factory vs. abstract Method
Simple factory mode: factory roles can be combined with specific product roles.
In the abstract factory mode, each specific factory class can have a static method, and its return value type is the specific factory class itself.
Simple factory vs. Factory method
The biggest advantage of the simple factory mode is that the factory class contains the necessary logic judgment, and the related classes are dynamically instantiated Based on the client selection conditions. For the client, the dependencies with specific products are removed. When the factory method mode is implemented, the client needs to decide which factory to instantiate to implement the computing class, and select whether the problem still exists. That is to say, the factory method identifies a client code by a simple internal logic. You want to add a function to change the factory class, but now you want to modify the client.
Factory method mode vs. Abstract Factory Mode
The factory method can be used flexibly as needed to evolve to an abstract factory.
The factory method mode has only one abstract product class, while the abstract factory mode has multiple. The factory class of the factory method mode can only create an instance of a specific product class, abstract Factory mode can create multiple.
V. Summary
All three factory models belong to the Creation Mode in the design mode. The main function is to help us extract the instantiation part of the object, optimize the system architecture, and enhance the scalability of the system.
Factory classes in simple factory mode generally use static methods to return different object instances by receiving different parameters. If you do not modify the code, it cannot be expanded.
The factory method provides a factory class for each product. Use different factory instances to create different product instances. Any product can be added to the same level structure.
Abstract Factory should deal with the concept of product family. For example, each automobile company may need to make cars, cars, buses at the same time, and each factory will create these different types of vehicles.