In "JavaScript Play Inheritance (ii)", I used the prototype inheritance method to implement JavaScript inheritance, and the prototype is what the mystery. In this article, I will focus on the prototype to start the discussion.
Aside from JavaScript, let's look at the familiar common object-oriented language. In 23 design patterns, you will remember that there is a design pattern--the prototype model. Let's look at the chart first:
(Original image quote: http://terrylee.cnblogs.com/archive/2006/01/16/317896.html)
Let's review the prototype pattern: see this graph, you will certainly notice this thousands of clone () method, this is the core of the prototype model. The prototype pattern is to use a prototype instance to create the type of object, and then copy the prototypes to create new objects.
In. NET, the implementation of this pattern is easy, and we just need to implement the ICloneable interface:
I remember in love left the lamp right in the line that Angel said such a word, anything to the mass production, this quality will not be guaranteed. This is a typical prototype model: mass production. Why is quality going down? The reason is that he is using the copy.
Look at the code:
class People:ICloneable
{
private string name;
private int age;
private List<string> friends = new List<string>();
public People(string name,int age,params string[] names)
{
this.name=name;
this.age=age;
foreach (string s in names)
{
friends.Add(s);
}
}
public string Name
{
get{return name;}
set{name=value;}
}
public int Age
{
get{return age;}
set{age=value;}
}
public List<string> Friends
{
get { return friends; }
set { friends = value; }
}
public object Clone()
{
return this.MemberwiseClone();
}
public override string ToString()
{
string ret = "name:"+name+" age:"+age+" friends: ";
foreach (string s in friends)
{
ret += s + ",";
}
return ret;
}
}