原型模式是属于创建型模式。允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。
它主要面对的问题是:“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口。
其实就是实现一下ICloneable借口(深复制和浅复制请自行处理,不在本文讨论范围)
C#代码:
using System;
namespace ConsoleApp2
{
public class Dove : ICloneable
{
private string _name;
private string _color;
private byte _age;
private byte _weight;
public string Name { get => _name; set => _name = value; }
public string Color { get => _color; set => _color = value; }
public byte Age { get => _age; set => _age = value; }
public byte Weight { get => _weight; set => _weight = value; }
public Dove(string name , string color, byte age, byte weight)
{
_name = name;
_color = color;
_age = age;
Weight = weight;
}
public override string ToString()
{
return string.Format("name:{0}, color:{1}, age:{2}, weight:{3}", _name, _color, _age, _weight);
}
public object Clone()
{
return this.MemberwiseClone();
}
}
public class Program
{
static void Main(string[] args)
{
Dove doveA = new Dove("gugu", "white", 12, 15);
Dove doveB = (Dove)doveA.Clone();
doveB.Color = "gray";
Console.WriteLine(doveA);
Console.WriteLine(doveB);
Console.WriteLine(String.Format("doveA {0} doveB", doveA == doveB ? "==" : "!="));
Console.Read();
}
}
}