Design Mode: Prototype Pattern)

Source: Internet
Author: User

Definition:

Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.
The prototype mode is a creation design mode. The prototype mode allows an object to create another custom object. You do not need to know how to create any details. The working principle is: by passing a prototype object to the object to be created, the object to be created is created by requesting the prototype object to copy them.

The prototype mode is another tool that can be used when the required generic classes are determined in the program but the specific classes need to be delayed until the runtime is determined. The similarity between the prototype and the generator mode is that all components or details of the final class are determined by Mo Jia clasming. The difference is that, in prototype mode, the target class is constructed by cloning one or more prototype classes, and then modifying or supplementing the details of the cloned class according to the expected behavior.

When the classes you need have different processing methods, you can use the prototype mode, for example, when analyzing strings expressed in different hexadecimal numbers. Let's consider an example. For the question of the swimming player competition mentioned above, we assume that contestants need to be sorted according to different rules. If a new instance is generated each time, it will occupy a high level of system resources.

Clone in C #

The only place where the clone method appears in C # Is In The ADO dataset processing. We create a dataset as the database query result, and its row pointer can move one row at a time. For some reason, if you need to keep the index at the two positions of the dataset, you need two indexes. C # The simplest way to solve this problem is to clone dataset.

DataSet cloneDS = ds.Clone();

Use prototype

Take the sorting of swimmers as an example to check the prototype. First define the sort mer class

/// <Summary> /// swimmers /// </Summary> public class timer mer: icomparable // sort contestants by using this API {private string name; private int age; Public timer mer (string name, int age) {This. name = Name; this. age = age;} Public String getname () {return name;} # region icomparable member public int compareto (Object OBJ) {merge mer Sw = OBJ as merge mer; return this. name. compareto (SW. name) ;}# endregion}

Next, we create a sort data class that contains the arraylist of the sort mer object read by the database.

View code

        public class SwimData:ICloneable
{
protected ArrayList swdata;
private int index;

public SwimData(ArrayList list)
{
swdata = list;
this.index = 0;
}

public void MoveFirst()
{
this.index = 0;
}

public bool hasMoreElements()
{
return index < swdata.Count ;
}

public void Sort()
{
swdata.Sort(0, swdata.Count, null);
}

public object Clone()
{
return this.MemberwiseClone();
}

public Swimmer getSwimmer()
{
if (index < swdata.Count )
{
return swdata[index++] as Swimmer;
}
else
return null;
}

}

Next we will add a method to initialize the data.

View code

        private void Init()
{
ArrayList list = new ArrayList();
list.Add(new Swimmer("name5", 25));
list.Add(new Swimmer("name6", 26));
list.Add(new Swimmer("name7", 27));
list.Add(new Swimmer("name8", 28));
list.Add(new Swimmer("name0", 20));
list.Add(new Swimmer("name1", 21));
list.Add(new Swimmer("name2", 22));
list.Add(new Swimmer("name3", 23));
list.Add(new Swimmer("name4", 24));

list.Add(new Swimmer("name9", 29));

data = new SwimData(list);
data.MoveFirst();
while (data.hasMoreElements())
{
Swimmer sw = data.getSwimmer();
listBox1.Items.Add(sw.GetName());
}


}

Run the program, such

 

Click "->" to sort contestants and add them to the list on the right.

View code

        private void button1_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
SwimData sd = data.Clone() as SwimData;
sd.Sort();
sd.MoveFirst();
while (sd.hasMoreElements())
{
Swimmer sw = sd.getSwimmer();
listBox2.Items.Add(sw.GetName());
}

DataSet ds = new DataSet();
ds = ds.Clone();
}

The result is as follows:

When you click the "<-" button again to fill the data back, you will find that the left side is not sorted.

View code

        private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
data.MoveFirst();
while (data.hasMoreElements())
{
Swimmer sw = data.getSwimmer();
listBox1.Items.Add(sw.GetName());
}
}

Why? We can see that our swim has implemented the icloneable interface. This. memberwiseclone () is a shortest copy and only copies references. It does not copy the object itself. Therefore, operations on the new class will be reflected in the new class. At this time, we mainly want to integrate the icloneable interface to implement the clone method if we create another new class. This is not satisfactory. A better solution is, cancel the interface for each class to implement the clone method, and change the processing process to let each class = accept the data in the clone and send class of the class. The following section describes how to modify the volume data class.

View code

            public void CloneMe(SwimData data)

{

swdata = new ArrayList();

ArrayList swd = data.getData();

for (int i = 0; i < swd.Count; i++)

{

swdata.Add(swd[i]);

}

}

Intended audience:
"Some objects with complex structures" are created. due to changes in requirements, these objects often face drastic changes, but they have stable and consistent interfaces.

Effects of Prototype

You can use the prototype mode to clone classes as needed. In this way, you can add or delete classes at runtime. You can change the internal data representation of a class at runtime, or specify a new object at runtime without creating a new class.

The difficulty in implementing the prototype with C # Is that if the class already exists, you cannot change it to add the clone method you need. In addition, classes that indirectly reference other classes cannot be cloned. Finally, the idea of the copy prototype means that you have sufficient access permissions to the data or methods in the class, so that you can modify them after cloning. This may require adding a data access method to the prototype so that the data can be modified after cloning.

 

Summary of Creation Mode

1. factory pattern selects a class instance from a series of related classes based on the factory data provided and returns.

2. abstract factory pattern is used to return one of a group of classes. In some cases, it actually returns a factory for a group of classes.

3. Builder pattern assembles a series of objects into a new object based on the data provided to him and its representation. Generally, the method used to assemble objects is determined by the factory.

When the cost of creating a new instance is high, copy or clone an existing class in the prototype pattern instead of creating a new instance.

Singleton pattern ensures that there is only one object instance and provides a global access point for this instance.

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.