zoukankan      html  css  js  c++  java
  • 创建型设计模式之原型模式(Prototype)

    结构  
    意图 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
    适用性
    • 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
    • 为了避免创建一个与产品类层次平行的工厂类层次时;或者
    • 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
     1  using System;
     2 
     3     // Objects which are to work as prototypes must be based on classes which 
     4     // are derived from the abstract prototype class
     5     abstract class AbstractPrototype 
     6     {
     7         abstract public AbstractPrototype CloneYourself();
     8     }
     9 
    10     // This is a sample object
    11     class MyPrototype : AbstractPrototype 
    12     {
    13         override public AbstractPrototype CloneYourself()
    14         {
    15             return ((AbstractPrototype)MemberwiseClone());
    16         }
    17         // lots of other functions go here!
    18     }
    19 
    20     // This is the client piece of code which instantiate objects
    21     // based on a prototype. 
    22     class Demo 
    23     {
    24         private AbstractPrototype internalPrototype;
    25 
    26         public void SetPrototype(AbstractPrototype thePrototype)
    27         {
    28             internalPrototype = thePrototype;            
    29         }
    30 
    31         public void SomeImportantOperation()
    32         {
    33             // During Some important operation, imagine we need
    34             // to instantiate an object - but we do not know which. We use
    35             // the predefined prototype object, and ask it to clone itself. 
    36 
    37             AbstractPrototype x;
    38             x = internalPrototype.CloneYourself();
    39             // now we have two instances of the class which as as a prototype
    40         }
    41     }
    42 
    43     /// <summary>
    44     ///    Summary description for Client.
    45     /// </summary>
    46     public class Client
    47     {
    48         public static int Main(string[] args)
    49         {                        
    50             Demo demo = new Demo();
    51             MyPrototype clientPrototype = new MyPrototype();
    52             demo.SetPrototype(clientPrototype);
    53             demo.SomeImportantOperation();
    54 
    55             return 0;
    56         }
    57     }
    原型模式
  • 相关阅读:
    [BTS] BizTalk host BizTalkServerApplication throttled because DatabaseSize exceeded the configured throttling limit.
    Linux sed 批量替换字符串方法
    MYSQL中的POSITION方法
    wc (Word Count)
    sudo
    关于数据库timestamp类型问题
    SQL中存储过程和自定义函数的区别
    数据库存储过程
    五 : springMVC拦截器
    四 : springMVC各种跳页面传值
  • 原文地址:https://www.cnblogs.com/ziranquliu/p/4669332.html
Copyright © 2011-2022 走看看