子类继承抽象的父类,一个子类可以通过自身构造函数克隆出与自己同类型的对象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prototype原型模式
{
abstract class Prototype
{
private string id;
// Constructor
public Prototype(string id)
{
this.id = id;
}
// Property
public string Id
{
get { return id; }
}
public abstract Prototype Clone();
}
class ConcretePrototype1 : Prototype
{
// Constructor
public ConcretePrototype1(string id) : base(id)
{
}
public override Prototype Clone()//Clone()函数,生成了与自己同类型的一个对象
{
// Shallow copy
return (Prototype)new ConcretePrototype1(this.Id);
}
}
class Program
{
static void Main(string[] args)
{
Prototype p1, c1;
p1 = new ConcretePrototype1("Design Pattern");
c1 = p1.Clone();
Console.WriteLine("Cloned: {0}", c1.Id);
Console.Read();
}
}
}
实例:
前几天,我很不幸把大门的钥匙给弄丢了,结果进不了家门。万幸的是,同学那儿还有一把,于是第二天我拿了他的那把去配钥匙。另外,他还让我顺便给他配一把房间的钥匙。现在配个钥匙真是简单,把钥匙给他,他直接找一个合适的钥匙胚子,把我的钥匙夹在配钥匙机的一端,胚子夹在另一端,一开电源,一把标尺比着我的钥匙齿型走一遍,砂轮就在胚子上复制出一把钥匙来!一分钟不到,两把新钥匙就搞定了!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 原型模式实例
{
public abstract class Key
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string owner;
public string Owner
{
get { return owner; }
set { owner = value; }
}
public Key(string name, string owner)
{
this.name = name;
this.owner = owner;
}
//钥匙复制自身的抽象定义
public abstract Key Clone();
public override String ToString()
{
return this.Name + ", 属于 " + this.Owner;
}
}
//大门钥匙
public class GateKey : Key
{
public GateKey(string owner) : base("大门 钥匙", owner) { }
public override Key Clone()
{
return new GateKey(this.Owner);
}
}
//橱柜钥匙
public class CabinetKey : Key
{
public CabinetKey(string owner) : base("房间 钥匙", owner) { }
public override Key Clone()
{
return new CabinetKey(this.Owner);
}
}
class Program
{
static void Main(string[] args)
{
Key oldGateKey, newGateKey, oldCabinetKey, newCabinetKey;
oldGateKey = new GateKey("同学");
newGateKey = oldGateKey.Clone();
newGateKey.Owner = "我";
oldCabinetKey = new CabinetKey("我");
newCabinetKey = oldCabinetKey.Clone();
newCabinetKey.Owner = "同学";
Console.WriteLine(oldGateKey.ToString());
Console.WriteLine(newGateKey.ToString());
Console.WriteLine(oldCabinetKey.ToString());
Console.WriteLine(newCabinetKey.ToString());
Console.Read();
}
}
}