创建型设计模式之原型模式(Prototype)

时间:2023-03-08 16:23:43
结构  创建型设计模式之原型模式(Prototype)
意图 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
适用性
  • 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
  • 为了避免创建一个与产品类层次平行的工厂类层次时;或者
  • 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
  using System;

     // Objects which are to work as prototypes must be based on classes which
// are derived from the abstract prototype class
abstract class AbstractPrototype
{
abstract public AbstractPrototype CloneYourself();
} // This is a sample object
class MyPrototype : AbstractPrototype
{
override public AbstractPrototype CloneYourself()
{
return ((AbstractPrototype)MemberwiseClone());
}
// lots of other functions go here!
} // This is the client piece of code which instantiate objects
// based on a prototype.
class Demo
{
private AbstractPrototype internalPrototype; public void SetPrototype(AbstractPrototype thePrototype)
{
internalPrototype = thePrototype;
} public void SomeImportantOperation()
{
// During Some important operation, imagine we need
// to instantiate an object - but we do not know which. We use
// the predefined prototype object, and ask it to clone itself. AbstractPrototype x;
x = internalPrototype.CloneYourself();
// now we have two instances of the class which as as a prototype
}
} /// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
public static int Main(string[] args)
{
Demo demo = new Demo();
MyPrototype clientPrototype = new MyPrototype();
demo.SetPrototype(clientPrototype);
demo.SomeImportantOperation(); return ;
}
}

原型模式