标签:
结构 | |
意图 | 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 |
适用性 |
|
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 }
标签:
原文地址:http://www.cnblogs.com/ziranquliu/p/4669332.html