原型模式:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。注意下例是浅表复制。
using System;
using System.Collections.Generic;
using System.Text;
namespace 设计模式
{
class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
abstract class Prototype
{
private string id;
private readonly Person cwd=new Person();
public void Setname(string name)
{
cwd.Name = name;
}
public string Getname()
{
return cwd.Name;
}
public Prototype(string id)
{
this.id = id;
}
public string Id
{
get { return id; }
}
public abstract Prototype Clone();
}
class ConcretePrototype1 : Prototype
{
public ConcretePrototype1(string id):base(id)
{
}
public override Prototype Clone()
{
//创建当前对象的浅表副本。方法是创建一个新对象,然后将当前对象的非静态字段复制到该新对象。如果字段
//是值类型的,则对该字段执行逐位复制。如果是引用类型,则复制引用,而不复制对象,即二者引用的是同一个
return (Prototype)this.MemberwiseClone();
}
}
class costume
{
//客户端程序
static void Main(string[] args)
{
ConcretePrototype1 prototype1 = new ConcretePrototype1("233");
prototype1.Setname("cwd");
ConcretePrototype1 copy1 = (ConcretePrototype1)prototype1.Clone();
Console.WriteLine("copy1.id:{0};prototype.id:{1}", copy1.Id, prototype1.Id);
Console.WriteLine("copy1.name:{0};prototype.name:{1}", copy1.Getname(), prototype1.Getname());
copy1.Setname("cwdgood");
Console.WriteLine("copy1.name:{0};prototype.name:{1}", copy1.Getname(), prototype1.Getname());
}
}
}
运行结果:
copy1.id:233;prototype.id:233
copy1.name:cwd;prototype.name:cwd
copy1.name:cwdgood;prototype.name:cwdgood