System Architecture skill-design model-factory Model

Source: Internet
Author: User
I. Opening

This article mainly describes the most classic Creation Mode-factory mode in the design mode. This article will explain the factory mode from the following points.

This article will give a detailed explanation and explanation from the above four aspects. Of course, some friends may have some shortcomings. Other friends may also ask us to learn from each other.

Ii. Summary

This article will mainly analyze how to use the project mode and when to use the project mode based on some examples in the project, and analyze the problems solved by the project mode, when can we use it in our actual project, or under what circumstances, we should consider using the factory model to solve the problems in the project. In general, we can understand the design model in this way, the design mode is a solution. In scenarios that we imagine or are similar to the application scenarios proposed by the design mode, such problems are common or common solutions.

This article still analyzes the position of the project model in the form of graphic explanations, and provides several flexible implementation solutions. The main implementation methods include configuration files, types, delegation, and features.

Iii. Outline

A. The beginning.

B. Summary.

C. Outline of this article.

D. Features and Use Cases of the factory model.

E. Implementation Scheme of the factory model.

F. Factory mode usage summary.

G, Series progress.

H. next release notice.

Iv. Features and Use Cases of the factory model 4.1. Introduction to the factory Model

The factory mode is the most typical mode in the creation mode. It is mainly used to create objects and reduce the new () operations when we use an object. I believe everyone has such confusion, currently, my projects are all in the process of program development. There are still a lot of new () operations in the performance layer, and no objects are created through the factory, on the one hand, it may be because we are relatively lazy and do not standardize the project coding format. On the other hand, it is because the project progress is tight and there is not so much time to complete the unified creation of the factory, of course, for such a factory that dynamically creates objects, we recommend that you use the "Abstract Factory mode" model that we will discuss later.

If you do not know what the factory model is for, we can use the following examples to explain, for example, we now have a mineral water processing factory, processing mineral water, we now know that there is mineral water, so when I batch produce mineral water, we will use the factory to batch produce, which is equal to the batch creation objects in our program. At this time, I have a lot of objects, that is, many tourists. Each of them needs a bottle of mineral water. At this time, if we compare tourists to different application modules, we need to use mineral water, so should I use the new () operation when every application uses this object ?, Undoubtedly, this is not a good solution. Let's take a look at the Graphical description?

In this case, when different tourists need mineral water, it is obvious that there is a difference between a new () mineral water and a processing factory. At this time, tourists should not be associated with mineral water, and they do not know how mineral water is produced or care about it.

So how should we solve this problem? When the design is based on object-oriented, the principle is low coupling between objects. Then, the reference relationships between objects can be decoupled by abstracting interfaces and using excuses for dependency to reduce system coupling. If I modify the object service name at this time, do I have to modify all the code that calls this object service application? This is required; otherwise, the program cannot be compiled. But what if we use the factory model? What is the difference? Let's take a look: The above is the case after the factory mode is added. Even if you have modified the class name, you only need to modify the new class in the factory, of course, if you use the form of the returned interface and do not modify the interface name, it is feasible to modify the class method and use the factory mode, without a doubt, the coupling between applications and objects is reduced, and the factory is used for decoupling to provide the adaptability of the program to respond to changes.

4.2 Use Cases of the factory Model

The factory mode is generally used to create a class of objects, instead of using a new () object every time you use it, you can create an object through the factory, this not only provides an entrance for unified object creation, but also greatly improves the maintenance and testability of the program. In general, the following scenarios are suitable for the factory model:

1. When the factory is responsible for creating a certain type of objects, or when the factory's responsibilities are relatively simple, if there are multiple types of objects, it is better to use the factory model to use the abstract factory.

2. Generally, a small number of accumulated objects can be created in the factory mode when different objects are created through type determination, such as multi-database support, when designing the data access layer, We dynamically create data access layer instances using simple object factory in the form of enumeration or configuration files.

3. Generally, when the type of an object is single, or the type is relatively small, using the factory mode to create an object can solve one type of problem. You can also create multiple factories through a general factory, and then Multiple factories are responsible for creating corresponding instances, which is similar to the directory structure we usually call.

Similar to the following, you can see at a glance that different levels of factories have different responsibilities and tasks.

V. Factory mode implementation Solution 5.1. Factory mode configuration file implementation.

Let's first look at the configuration content of the configuration file:

<DatabaseInfo><ConnKey>default</ConnKey><DataBaseType>MSSQLServer</DataBaseType></DatabaseInfo>

Define the unified interface of the object instance to be created:

/// <Summary> /// all data access interfaces /// </Summary> publicinterface idbaccess {}

Specific classes that implement this interface:

Publicclass sqlserver: idbaccess {// related method public system. Data. sqlclient. sqlconnection connection {get {returnnew system. Data. sqlclient. sqlconnection ();}}}

Creates an object instance at the data access layer whose return type is idbaccess:

Publicclass dbfactory {public idbaccess create () {idbaccess instance = NULL; system. XML. xmldocument Doc = new system. XML. xmldocument (); Doc. loadxml (""); xmlelement root = Doc. documentelement; // the XML document's root node xmlnode = root. selectsinglenode ("databasetype"); Switch (node. innertext) {Case "sqlserver": instance = new sqlserver (); break; Case "oracle": instance = new Oracle (); break; default: break ;} return instance ;}}

The specific console output test code is as follows:

Class program {staticvoid main (string [] ARGs) {dbfactory factory = new dbfactory (); idbaccess dbaccess = factory. create (); // use the corresponding data access object .}}

5.2. Implemented through enumeration.

After enumeration is implemented, the code for creating a factory class is as follows:

publicclass DBFactory{public IDbAccess CreateByEnum(DbType dbType){IDbAccess dbAccess =null;switch ((int)dbType){case (int)DbType.SQLServer:dbAccess=new SQLServer();break;case (int)DbType.Oracle:dbAccess =new Oracle();break;case (int)DbType.Access:dbAccess =new Access();break;default:break;}return dbAccess;}}

The enumerated code is as follows:

publicenum DbType{SQLServer=0,Oracle=1,Access=2}

Corresponding console test code:

Staticvoid main (string [] ARGs) {dbfactory factory = new dbfactory (); idbaccess dbaccess = factory. createbyenum (dbtype. sqlserver); // use the corresponding data access object .}

5.3 complex advanced factory Model

We just defined a factory which is responsible for creating all subclass objects. If our factory requirements can meet the requirements of adding new objects, we must modify the factory code, how can we do this? We can do this.

Each type of object is created by a factory corresponding to this type, you only need to modify the files involved in the corresponding factory even if you add or modify the objects later. However, this also has a major drawback: there are too many factory classes and it is difficult to maintain them. The advantage is that you can dynamically add new object types without affecting the previous creation. Let's take a look at the corresponding code based on the Several Types shown in the figure. First, define the unified interface of the object and the interface of the factory. First, let's look at the Unified Definition of the object interface:

Publicinterface icomobject {// <summary> // importance level /// </Summary> /// <returns> </returns> int importlevel ();}

Unified Definition of factory interfaces:

publicinterface IComFactory{IComObject Create();}

Let's take a look at the specific object implementation and factory implementation. Here we take the book in as an example to illustrate the creation process:

publicclass BookFactory : IComFactory{public IComObject Create(){returnnew Book();}}

Specific Object implementation code-implement the icomobject object interface:

publicclass Book : IComObject{publicint ImportLevel(){return0;}}

Let's take a look at the specific program call code:

Staticvoid main (string [] ARGs) {icomfactory factory = new bookfactory (); icomobject book = factory. Create (); // use the corresponding data access object .}

In the above form, we can see that if I add a product later, for example, I want to add the product object to the system, then we only need to add the corresponding object implementation class and factory implementation class, which will not affect other places, as described above, the method of creating all object instances in a factory undoubtedly provides the ability to create new object types.

Vi. Factory model usage Summary

Through the simple example above, it is estimated that it is easy and easy for the experts to understand. In fact, it is also very simple. People who do not know the factory model should also be able to understand the content described, the two methods described earlier in this article mainly aim at the simple factory mode and the simple factory mode, which do not conform to the high cohesion principle, because the creation of all objects is completed in the same class, the logic is too complex. In the subsequent factory model, the responsibilities of each factory are further refined, and each factory is only responsible for creating specific object type instances. This also provides a good extension for adding new object types in the future. This article does not provide the implementation scheme of the feature + delegated factory. I will explain it in the abstract factory in the next article, we will also provide implementation solutions for the abstract factory mode based on configuration files, features, and delegate methods. Of course, I will give very simple examples. I hope you can understand them at a glance, in actual projects, experts may think that I am too simple to talk about. On the one hand, it is because I have not organized my own ideas, and the time is short. On the other hand, it is because my own capabilities are limited, please give us more valuable comments. Let's summarize the content described in this article;

The previous section describes the implementation scheme of the simple factory model in 2. The creation of objects through configuration files and enumeration is actually completed based on the object type, or through reflection. Here is a simple implementation:

public IDbAccess Create(string TypeName){Type type = Type.GetType(TypeName);IDbAccess obj = (IDbAccess)Activator.CreateInstance(type);return obj;}

In fact, it is such a short code that provides key code implementation. It may need to be adjusted during actual operation. In general, it is convenient to use a simple factory when there are not many types of projects. When you frequently add different types of objects to a project, consider using the factory mode to meet such dynamic change requirements.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.