Design Pattern series-creator Pattern

Source: Internet
Author: User
ArticleDirectory
    • I. Review of the previous Article
    • Ii. Summary
    • Iii. Outline
    • Iv. Features and Use Cases of the Creator Model
    • 5. Implementation Scheme of the Creator Mode
    • Vi. creator mode usage Summary
    • VII. Progress of the series.
    • 8. next announcement.
I. Review of the previous Article

In the previous article, we mainly talked about the abstract factory model and factory model. The application scenarios and advantages and disadvantages of this mode are analyzed, and some implementation ideas and solutions are provided. Let's review the following:

Abstract Factory mode: a factory is responsible for creating all types of objects and supports seamless creation of new types of objects. This is achieved through the configuration file and dictionary ing. However, it may be inefficient and can be optimized.

In the previous article, we also provided the delegated factory implementation form, which is more flexible than the previous simple factory model and factory model, it is particularly suitable for creating objects with dependency or composite relationships.

In the previous article, many of my friends have put forward some comments and suggestions. First of all, I would like to thank everyone for their support and encouragement. Some of my friends have suggested that the pictures I have drawn are not professional enough, how do professionals use UML modeling diagrams? I agree with this statement, but I found that

In addition, you can better understand the visual image at a glance.CodeOf course, a good UML diagram can clearly express the design idea and the major implementation, but to be honest, I look at it as a little class, especially when the UML diagram is complex. So I will use this general image for the moment.

To express the thought of the design model I understand, to see what people think and opinions, if we talk about the UML diagram, then the relevant model in the future, I will mainly draw with UML professional diagrams.

I would like to summarize the following solutions when we may use design patterns or system architecture in future projects, we can design it when considering the low coupling of the system:

Basically, the above situations can be grasped. Basically, the system designed is at least available. I wonder if you have any more comments and suggestions. If you have any questions, I will prepare them.

Note in the article.

Ii. Summary

This article mainly describes the Creator mode in the creation mode. The Creator mode is the most responsible design mode in the creation mode. The Creator is responsible for building each part of an object, we can understand the creation process in this way.

The Creator mode is similar to the creation of such objects that are basically fixed with a step, but the specific form in each step can change. Maybe this is too abstract. Let's understand it. I feel the easiest way to understand is graphical.

Not only is it easy to accept, but it also brings a deep image. Do you have the same feelings with me? The following is a simple example, which can be illustrated through a graphical process: here we take the most common cooking as an example:

Maybe the process I provided here is just what I personally understand or see. It doesn't mean all. Haha, it's just a case description.

Iii. Outline

A. Review in the previous article.

B. Summary.

C. Outline of this article.

D. Features and Use Cases of the Creator mode.

E. Implementation Scheme of the Creator mode.

F. Summary of use of the Creator mode.

G, Series progress.

H. next release notice.

Iv. Features and Use Cases of the Creator Model

The Creator mode is mainly used to create complex objects. The creation steps of these objects are basically fixed, but the components of specific objects can be freely changed. There are many examples in reality, however, it may be easier for everyone to understand that I

We can understand that the various parts of these hardware devices, whether the CPU is Intel or AMD, are Asus or small-sized, whether the hard disk is Western data or Seagate, you actually want to express it

It means that the specific components of an object can be changed, but we may find that the process of organizing these components is relatively fixed, then we can use the Creator mode, and we introduce a leader (Director)

Guides the assembly process of this object. A graphical process can be used to describe the process as follows:

The above describes the approximate Production Process of a garment. The production sequence may change, or

The production of hats and jackets will change, but the assembly process of clothing is basically not changed. Hats, jackets, and trousers are all needed, at this time, we can guide the process of assembly, and then we can abstract each part

And create different hats according to different implementations.

5. Implementation Scheme of the Creator Mode
5.1 Implementation of the classic creator Mode
      • We first provide an implementation form of the classic creator mode, and then propose several improvement solutions for this classic mode, the clothing process described above is used as an example to illustrate the principles and ideas of the Creator mode. I hope that you can flexibly apply the process to actual projects. Achieve the purpose of learning to use.

Let's take a look at the specific code implementation:

/// <Summary> /// create all the construction step interfaces of the Object Organization // </Summary> Public interface ibuider {void builderpart1 (); void builderpart2 (); void builderpart3 ();}

Define a clothing object:

/// <Summary> /// clothing object /// </Summary> public class dress {/// <summary> /// build the hat /// </Summary> public void buildhat () {Throw new notimplementedexception () ;}/// <summary> /// build a coat /// </Summary> Public void builderwaist () {Throw new notimplementedexception ();} /// <summary> /// build pants /// </Summary> Public void buildertrousers () {Throw new notimplementedexception ();}}

To create an object, follow these steps:

Public class builder: ibuider {private dress _ dress; Public Builder (dress Dress) {This. _ dress = dress;} public void builderpart1 () {This. _ dress. buildhat ();} public void builderpart2 () {This. _ dress. builderwaist ();} public void builderpart3 () {This. _ dress. buildertrousers ();} public dress build () {return this. _ dress ;}}

The instructor guides the creation of objects, and the creation of specific objects depends on the corresponding methods provided by the objects themselves. Builder only calls the methods of objects to complete the Assembly steps. The builder provides a method to return the complete object after construction. The above method is

Build () method.

/// <Summary> // instructor // </Summary> public class director {public void build (ibuider builder) {builder. builderpart1 (); builder. builderpart2 (); builder. builderpart3 ();}}

Through the above Code, we provide the core code form of the classic creator mode, so there are undoubtedly the following disadvantages for the above:

1. The ibuilder interface must define a complete assembly process. Once defined, it cannot be modified dynamically.

2. There is a certain dependency between builder and specific objects. Of course, flexibility can be achieved through decoupling through interfaces.

3. the builder must know the specific process.

How can we solve the above problems? I think the previous creation mode has given me enough experience to provide flexibility through configuration files or other forms.

    • 5.2. creator Mode features + delegate implementation
For the example above, we can consider the following methods for improvement:

We first define a delegate to construct each object part, and the parameters of this method are dynamically changed:

/// <Summary> /// define the delegate of the general construction part /// </Summary> Public Delegate void buildhandler (Params object [] items );

We identify the construction steps of each part of the object by defining tags.

/// <Summary> /// mark each step of the object /// </Summary> [attributeusage (attributetargets. method, allowmultiple = false)] public class buildattriort: attribute {private methodinfo hander; private int stepsort; Public methodinfo buildhandler {get {return this. hander;} set {This. hander = value ;}} public int stepsort {get {return this. stepsort;} set {This. stepsort = value ;}}}

Unified interface for constructing objects

/// <Summary> /// create all the construction step interfaces of the Object Organization // </Summary> Public interface ibuider {void build <t> () where T: class, new ();}

The following code shows the specific builder cache implementation scheme.

 
Public class commonbuilder: ibuider {// <summary> // cache the specific construction steps of each object /// </Summary> private dictionary <type, list <buildhandler> steps = NULL; Public void build <t> (T ob) where T: Class, new () {// read the list of items of the specified type from the cache <buildhandler> handlers = steps [typeof (t)]; foreach (buildhandler handler in handlers) {handler ();}}}

Obtains the list of all the methods with custom feature tags within a type.

Public list <methodinfo> getmethodinfolist <t> () where T: Class, new () {// read the list of items of the specified type from the cache <methodinfo> methods = new list <methodinfo> (); t target = new T (); methodinfo [] methodlist = typeof (t ). getType (). getmethods (); buildattribute [] attributes = NULL; foreach (methodinfo info in methodlist) {attributes = (buildattribute []) info. getcustomattributes (typeof (buildattrites), true); If (attributes. length> 0) methods. add (Info);} return methods ;}

To obtain all the features, you can use this method to obtain a list of all methods with this feature marked and the corresponding steps:

Public list <buildattriist> getbuildattributelist <t> () where T: Class, new () {list <buildattrites> attributes = new list <buildattribute> (); buildattribute [] attributelist = NULL; buildattribute attribute = NULL; foreach (methodinfo info in this. methods) {// set the attributelist = (buildattribute []) info method to be executed in the feature. getcustomattributes (typeof (buildattrites), true); If (attributelist. length> 0) {attribute = attributelist [0]; attribute. buildhandler = Info; attributes. add (attribute) ;}// cache step steps. add (typeof (t), attributes); Return attributes ;}

Call code implementation in a specific build:

Public t build <t> (T ob) where T: Class, new () {list <buildattriist> attributelist = getbuildattributelist <t> (); t target = new T (); // construct the object process foreach (buildattribute item in attributelist) {item. buildhandler. invoke (target, null);} return target ;}

In this way, we have completed a general code implementation of tag-based automatic discovery of a certain type of TAG method step. You may feel that this method is quite troublesome, so we still have no better improvement solutions? Because I still feel it every time I mark it

It is quite troublesome, and the code volume distribution is also extensive. I want to use the unified configuration management method. Of course, it is also possible, so we can use the following method for expansion.

    • 5.3 creator mode configuration file implementation
In the abstract factory model above, we mainly use this method to achieve configuration flexibility and scalability. In fact, the Creator is the same, let's take a look at the configuration file. I want to know about the configuration file. The specific application code is shown in the following figure:

Here is an example of a parent-child node in the configuration file:

<? XML version = "1.0" encoding = "UTF-8"?> <Build> <buildclass name = "classname" type = "classtype"> <buildstep steporder = "1" methodname = "methodname1"/> <buildstep steporder = "2" methodname =" methodname2 "/> </buildclass> <buildclass name =" classname1 "type =" classtype1 "> <buildstep steporder =" 1 "methodname =" methodname1 "/> <buildstep steporder =" 2 "methodname =" methodname2 "/> </buildclass> </build>

We will read all the steps in the configuration file in the build implementation and put them in the dictionary. Sample Code

/// <Summary> /// interface for creating all construction steps of the Object Organization /// </Summary> public class buider: ibuider {private dictionary <type, list <methodinfo> steps = NULL; Public buider () {steps = new dictionary <type, list <methodinfo> (); // read the configuration file! // Retrieve the class name and method name in the configuration file, and then retrieve all methods of this type through reflection. add them to the // step list according to the steps and method names in the configuration, then cache it to the dictionary for steps. add (type. getType (""), new list <methodinfo> ();} public t build <t> () where T: Class, new () {T target = new T (); // find the corresponding cache list from the dictionary and execute the construction process list <methodinfo> List = steps [typeof (t)]; // execute the construction foreach (methodinfo info in list) {info. invoke (target, null) ;}return target ;}}

You can complete the corresponding building process by configuring the above steps. At this time, our mentor's work is simple, that is, simply using the general method in build

 
Public class director {public void build <t> (ibuider builder) where T: Class, new () {builder. Build <t> ();}}

The general implementation scheme of the Creator mode is completed through the above steps.

Vi. creator mode usage Summary

Based on the several different implementation schemes given above, we know that the Creator mode is a "refined" Construction Process for object construction. The construction of each part may change, however, the object organization process is fixed.

Without a doubt, it increases our design flexibility. When we build complex objects, if we find that each part may change, when there are multiple building steps, we can consider using the Creator mode. Compared with what we described earlier

The factory and the abstract factory mode are very different. We found that the Creator is suitable for the creation of such complex objects, and the abstract factory may not be able to complete such assembly work, in addition, the Creator mode calls and organizes and coordinates the internal creation methods of complex objects.

Control the order of each part of the object. A brief description of the Creator is as follows:

If you have better comments or ideas, please give them a discussion, you are welcome to provide valuable comments and suggestions.

VII. Progress of the series.
Creation type

1. Design Mode of system architecture skills-one-piece Mode

2. Design Mode of system architecture skills-factory Mode

3. Design Mode of system architecture skills-Abstract Factory Mode

4. Design Mode of system architecture skills-creator Mode

5. Design Mode of system architecture skills-prototype mode

Structural

1. Design Mode of system architecture skills-Combination Mode

2. Design Mode of system architecture skills-appearance Mode

3. Design Mode of system architecture skills-adapter Mode

4. Design Mode of system architecture skills-Bridge Mode

5. Design Mode of system architecture skills-decoration Mode

6. Design Mode of system architecture skills-enjoy the Yuan Model

7. Design Mode of system architecture skills-Agent Mode

Behavior Type

1. Design Mode of system architecture skills-command mode

2. Design Mode of system architecture skills-Observer Mode

3. Design Mode of system architecture skills-Strategy Mode

4. Design Mode of system architecture skills-responsibility Mode

5. Design Mode of system architecture skills-template Mode

6. Design Mode of system architecture skills-intermediary Mode

7. Design Mode of system architecture skills-interpreter Mode

8. next announcement.

The next article will describe the prototype mode, which is also one of the distinctive design modes in the creation mode. This mode is to generate a new object by cloning an existing object, of course, the replication objects here can be two types: Deep replication and shallow replication.

In the summary of this series, if you have good ideas or ideas, please put forward them. I hope you will give more valuable comments. Please also point out the mistakes. Please continue to support them.

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.