码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-23 09:28:23      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

结构  技术分享
意图 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
适用性
  • 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
  • 为了避免创建一个与产品类层次平行的工厂类层次时;或者
  • 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

 

技术分享
 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     }
原型模式

 

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

标签:

原文地址:http://www.cnblogs.com/ziranquliu/p/4669332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!