C#设计模式之Prototype

添加人:iyond六级(3302分)   添加时间:2007-05-18    阅读次数:1427  收藏此教程
名称: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;
        }
    }
}
1页 第1上一页1下一页
相关的教程: CSharp 设计模式 Prototype
收藏此教程

当前平均分: 0.0(0 次打分)

-5-4-3-2-1012345
评论主题
您的大名
您的评论
验证码 点击换一个验证码
知识库搜索: