简要说明
原型模式定义一个原型接口,其中有克隆自身的方法及此接口所有实现及后代都应该具有的方法的定义。其实现及实现的后来均重写克隆方法,使得克隆方法返回自身的一个克隆,克隆对象具有母对象的所有特性。客户类使用不同对象的克隆实现对象的创建。原型模式适用于需要创建许多来自同一抽象的不同后代对象,同时希望通过已有对象克隆来创建新对象的场合。
结构类图
结构示例代码
/**************************************************
*
- Design Pattren Quick Start
- 04 Prototype - 原型
**************************************************/
namespace DesignPatternQuickStart.Prototype
{
///
/// 原型接口
///
interface IPrototype
{
IPrototype Clone();
}
///
/// 具体原型类A
///
class PrototypeA : IPrototype
{
public string Member1 { get; set; }
public IPrototype Clone()
{
PrototypeA cloneObject = new PrototypeA();
cloneObject.Member1 = Member1;
return cloneObject;
}
}
///
/// 具体原型类AA
///
class PrototypeAA : PrototypeA
{
public string Member2 { get; set; }
public new IPrototype Clone()
{
PrototypeAA cloneObject = new PrototypeAA();
cloneObject.Member1 = Member1;
cloneObject.Member2 = Member2;
return cloneObject;
}
}
///
/// 客户类
///
class Client
{
public void OpreateMethod()
{
IPrototype prototypeA1 = new PrototypeA();
IPrototype prototypeA2 = prototypeA1.Clone();
IPrototype prototypeAA1 = new PrototypeAA();
IPrototype prototypeAA2 = prototypeAA1.Clone();
}
}
}