Design Pattern series-prototype Pattern

Source: Internet
Author: User
ArticleDirectory
    • I. Review of the previous Article
    • Ii. Summary
    • Iii. Outline
    • Iv. features and application scenarios of the prototype
    • 5. Deep replication and light Replication
    • Vi. Implementation Scheme of the prototype model
    • VII. Usage of Prototype
    • 8. Series progress
    • IX. next announcement
    • 10. Download demo
I. Review of the previous Article

In the Creator mode, we mainly talk about Several implementation schemes of the creator and the scenarios and features of the application of the Creator mode. The Creator mode is suitable for creating complex objects, and each of these objects

The detailed creation steps of components can be dynamic, but the process of assembling each object may be relatively fixed or the process of creating an object is fixed, then, through the Creator

The mode can well solve the creation of such complex objects, and may have this requirement in our life or projects, so using the Creator mode is undoubtedly a good choice.

In the Creator mode, the construction of each object component is an internal method provided by the object itself. The specific creator only calls the construction method of the corresponding internal component of the object to be created.

The execution sequence of the internal build methods of these objects to complete the object construction. When our customer applicationsProgramTo call this creator, we only need to provide unified

The Creator's access portal, which can be injected by constructors or configuration files.

Ii. Summary

This article mainly describes a special mode in the Creation Mode-prototype mode. The biggest feature of this mode is to clone an existing object, there are two types of clone results:

It is a shallow replication, and the other is deep replication. Here we will also discuss the principles of deep replication and shallow replication, which may make it easier for you to understand the usage of this prototype. We all know that the creation mode is generally

This is used to create a new object, and then we use this object to complete some object operations. We can quickly create an object through the prototype mode without providing a special new () fast operation

Quickly create an object, which is undoubtedly a very effective way to quickly create a new object. This article will introduce the following aspects:

1. Use Cases and features of the prototype

2. Principles of light replication and deep Replication.

3. Examples: shallow replication and deep replication.

4. Implementation Scheme of the prototype mode.

5. Summarize the prototype mode.

Here we first provide a schematic diagram of the prototype:

Iii. Outline

A. Review in the previous article.

B. Summary.

C. Outline of this article.

D. features and application scenarios of the prototype mode.

E. Deep replication and light replication.

F. Implementation Scheme of the prototype mode.

G. Summary of prototype usage.

H. Series progress.

I. Coming soon.

Iv. features and application scenarios of the prototype

the main idea of the prototype mode is to clone a new object based on an existing object. Generally, a clone method is provided internally for an object to return a copy of the object, this creates a pair

compared with the previous several types of creation modes, both the factory model and abstract factory described earlier encapsulate specific new operations through the factory and return a new pair.

sometimes it is not worthwhile to create an object through a factory like this, especially in the following scenarios, the prototype mode may be simpler and more efficient.

1. If our object type is not determined at the beginning, but determined at runtime, it is easier to clone a new type from this type of object. This

how to understand. For example, when we filter records in a able and put them in a new datatable, we know that if the two able architectures are different, we must

assign values manually. Otherwise, data cannot be imported as follows:

Code and description

Public class datatabledemo
{
Public void clonetest ()
{
String plain text = "select * from table ";
Datatable dt = new datatable ();
// Return a datatable object by executing the preceding plain text;

// At this time, we can copy a new able in the following form, instead of creating a datatable first, and then add the loops displayed for each column to the new datatable,

// This is a huge workload.
Datatable dt1 = DT. Clone ();
// Clone a new object dt1.

# Region does not clone a new able.

Datatable dt2 = new datatable ();

Foreach (datacolumn column in DT. columns)
{
Dt2.columns. Add (column. columnname );
}

# Endregion
}
}

2. Sometimes we may need a copy of an object in a certain state in the actual project. This premise is very important. How can we understand this? For example, sometimes we need to compare an object

If the status after processing and the status before processing have changed, we may need to clone a copy of the status of this object before performing some processing, then, wait for the execution status to be matched.

Such applications often appear in projects.

If we have such requirements, we often encounter such problems in the design of the ORM framework. When we are dealing with the editing status of an object, we want the Updates generated by the framework.

The SQL statement of the database does not contain columns whose data columns have not changed. do not appear in the update statement. In this case, a possible solution is to clone an object before editing, and submit it after editing.

When the corresponding statement is generated, compare the cloned object to see if the data has changed. If some data columns of the object have changed, then, update the changed data columns.

Of course, the above is just a simple implementation scheme, but the efficiency is not very high. I will not discuss many good schemes. Here we just want to illustrate the available scenarios of the prototype model.

If you are not familiar with the above method or are tired of reading the text, you can see the figure below, which should be clear.

In this case, the prototype mode may be better.

3. When we are dealing with some objects that are relatively simple and have little difference between objects, there may be several fixed attributes that are different, we may be more appropriate to use the prototype mode, for example

The colorful color of live rainbow, etc. We only need to clone a new color object based on an existing color object, and then modify the specific color value to meet the requirements, then, if

The newly created factory and abstract factory model we talked about earlier introduce new dependencies and increase the complexity. For example, the clone of colors in our life:

We can clone all other colors in red, just modify the corresponding individual attributes, far more than creating a new pair.

And then assign values to each attribute of the object to make it simple and convenient. Of course, if we do not need to copy a new object based on the existing object, or we need a clean, empty pair.

For example, my first choice is the factory model or the abstract factory model.

 

5. Deep replication and light Replication

Since this article describes the specific application of the prototype model, we must first understand the deep replication and shallow replication, otherwise we will not understand the specific cloning process and cloned

Object details.

Each built-in. Net freamwork inherited from system. object has a member protection method:

//
// Summary:
// Create a superficial copy of the current system. object.
//
// Return result:
// The superficial copy of the current system. object.
[Securitysafecritical]
Protected object memberwiseclone ();

The system provides a built-in method for copying objects. However, this method returns a copy of a shortest copy object, and. NET provides a system. icloneable interface for me,

By implementing this interface, we can provide custom cloning methods for objects.

To understand the differences between shallow replication and deep replication, I must first understand the differences between the two ,. net itself provides the method of shallow replication, and the method of deep replication needs to implement its own interface.

Let's take a look at the situation of objects and object copies after the shortest copy:

Let's take a look at the situation of the objects and object copies of deep replication:

Based on the above description, we should have a rough understanding of the differences between shallow replication and deep replication. Then we will combine the program code to separate

You may be more familiar with specific applications. Let's take a look at the simplest case of shortest replication and deep replication. Here is an example:

We define a cup class and define several simple properties of the Cup. The Code is as follows:

/// <Summary>
/// Cup
/// </Summary>
Public class cup: icloneable
{
Private double _ RL;
Private int _ height;
Private factory _ factory;
/// <Summary>
/// Height
/// </Summary>
Public int height
{
Get
{
Return _ height;
}
Set
{
_ Height = value;
}
}

/// <Summary>
/// Capacity
/// </Summary>
Public double RL
{
Get
{
Return _ RL;
}
Set
{
_ RL = value;
}
}

/// <Summary>
/// Manufacturer
/// </Summary>
Public factory Factory
{
Get
{
Return _ factory;
}
Set
{
_ Factory = value;
}
}

# Region icloneable Member

Public object clone ()
{
Return this. memberwiseclone ();
}

# Endregion
}

Specific test code:

Class Program
{
Static void main (string [] ARGs)
{
Cup = new cup ();
Cup. Height = 2;
Cup cup1 = (cup) Cup. Clone ();

Cup1.height = 1;
Console. writeline (cup. Height = cup1.height );
System. Threading. thread. Sleep (10000 );
}
}

The running result is as follows:

To sum up, we know that for members of the value type, the shortest copy is also a re-created member in the copy, corresponding to the memory stack, allocating new memory space. For the reference type

When the object and the object copy share the same referenced object, no matter whether the corresponding referenced member is modified in the object or the object copy, then the reference type members will change.

Because two objects direct to the same memory address, any modification operation will change.

So how can we modify the implementation of this class to achieve deep replication?

The above clone method is implemented as follows:

Public object clone ()
{
Cup = (cup) This. memberwiseclone ();
Factory factory1 = new factory ();
Factory1.factoryname = This. Factory. factoryname;
Cup. Factory = factory1;

Return cup;
}

This completes the deep replication of objects, whether it is a value-type member or a reference-type member. Such an object and object copy modifies any member attribute, will not affect object change

Value.

Vi. Implementation Scheme of prototype mode 6.1 classic Implementation of prototype mode

Let's take a look at the Classic Implementation of the prototype model. Here we have used color as an example to illustrate the classic implementation.

Define an interface to express all color objects:

Public interface icolordemo
{
Icolordemo clone ();

Int red
{
Get;
Set;
}
Int green
{
Get;
Set;
}
Int blue
{
Get;
Set;
}
}

The specific red implementation code is provided here:

Public class redcolor: icolordemo
{
Private int red;
Private int green;
Private int blue;
Public int red
{
Get
{
Return this. Red;
}
Set
{
This. Red = value;
}
}
Public int green
{
Get
{
Return this. Green;
}
Set
{
This. Green = value;
}
}
Public int blue
{
Get
{
Return this. blue;
}
Set
{
This. Blue = value;
}
}

# Region icolordemo Member

Public icolordemo clone ()
{
Return (icolordemo) This. memberwiseclone ();
}

# Endregion
}

Because the above colors are all configured in different proportions of RGB, I have defined three integer variables, so I will only demonstrate them here. The specific test code is as follows:

Static void main (string [] ARGs)
{
Icolordemo color = new redcolor ();
Color. Red = 255;

Icolordemo color1 = color. Clone ();
Color1.blue = 255;

Console. writeline (color. Blue = color1.blue );
System. Threading. thread. Sleep (10000 );
}

The returned result is false. The modification of the object copy does not affect the status of the object.

6.2 Other Situations of Prototype

The above describes the simple situation of shallow replication. Let's analyze the implementation of the deep replication prototype. The situation of deep replication may be relatively complicated, because it is possible that the object is

When there is an inheritance or reference relationship, we may need to pay attention to it during deep replication. Of course, this is also a test for us. In general, deep replication can use the simple one I mentioned above.

When copying objects in depth, you can also copy objects in the form of serialization. The following describes how to implement the prototype through serialization:

We first provide the help classes for serialization and deserialization:

For example, we use binary format for serialization. We all know that the serializable classes must be marked to identify whether they can be serialized or defined on member attributes.

/// <Summary>
/// Serialization and deserialization auxiliary classes
/// </Summary>
Public class serializablehelper
{
Public String serializable (object target)
{
Using (memorystream stream = new memorystream ())
{
New binaryformatter (). serialize (stream, target );

Return convert. tobase64string (stream. toarray ());
}
}

Public object derializable (string target)
{
Byte [] targetarray = convert. frombase64string (target );

Using (memorystream stream = new memorystream (targetarray ))
{
Return new binaryformatter (). deserialize (Stream );
}
}

Public t derializable <t> (string target)
{
Return (t) derializable (target );
}
}

The following is a simple sample code, or the above color object is used as an example. Modify the clone method in the color class.

# Region icolordemo Member

Public icolordemo clone ()
{
String target = serializablehelper. serializable (this );
Return serializablehelper. derializable <icolordemo> (target );
}

# Endregion

The test code of the program is as follows:

Static void main (string [] ARGs)
{
Icolordemo color = new redcolor ();
Color. Red = 255;

Icolordemo color1 = color. Clone ();
Color1.red= 234;

Console. writeline (color. Blue = color1.blue );
System. Threading. thread. Sleep (10000 );
}

The running result of the program is false. The two objects must be different. A new object is formed through serialization and deserialization. In fact, as long as the project needs to use the prototype mode for object replication

Deep replication can all be performed in the form of serialization.

VII. Usage of Prototype

The prototype mode is the most special mode in the creation mode. The specific creation process is provided by the object itself. In this way, in many scenarios, we can easily and quickly build new

Objects, as described in the previous analysis, we may use object cloning to achieve better results than other creation modes, the cost is much lower. For example,

The prototype can seamlessly scale the system. Why? For example, if another created factory adds an object type

Without a doubt, we all need to modify the form of code. This is undoubtedly dangerous for common public applications, so through the prototype mode, you can solve this problem.

Because the type itself can implement this method, but it also has some shortcomings. Every object implements this method, which is undoubtedly a huge workload, however, in some special environments

In the project, the prototype mode may be a good choice.

8. Series progress
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

IX. next announcement

The next article will describe the appearance mode. This mode is also one of the distinctive design modes in the structure mode. This mode encapsulates some fine-grained items in the existing system through the appearance object,

When you access these methods in an application, a unified access portal is provided in the form of a appearance class, and the specific details are not required by the application, this will reduce the complexity of program calls.

Due to my limited level, insufficiency, or errors, please criticize and correct me. Please continue to support me. Thank you.

10. Download demo

Download this demo

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.