C#设计模式之Prototype

名称:Prototype
结构:
 
意图:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
 
适用性 :
  1. 当要实例化的类是在运行时刻指定时,例如,通过动态装载;
  2. 为了避免创建一个与产品类层次平行的工厂类层次时;
  3. 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。  
示例代码
// Prototype
namespace Prototype_DesignPattern
{
    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 0;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值