结构 |
意图 | 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 |
适用性 |
|
1 using System; 2 3 // These classes could be part of a framework, 4 // which we will call DP 5 // =========================================== 6 7 abstract class DPDocument 8 { 9 abstract public void Dump(); 10 } 11 12 abstract class DPWorkspace 13 { 14 abstract public void Dump(); 15 } 16 17 abstract class DPView 18 { 19 abstract public void Dump(); 20 } 21 22 abstract class DPFactory 23 { 24 abstract public DPDocument CreateDocument(); 25 abstract public DPView CreateView(); 26 abstract public DPWorkspace CreateWorkspace(); 27 } 28 29 abstract class DPApplication 30 { 31 protected DPDocument doc; 32 protected DPWorkspace workspace; 33 protected DPView view; 34 35 public void ConstructObjects(DPFactory factory) 36 { 37 // Create objects as needed 38 doc = factory.CreateDocument(); 39 workspace = factory.CreateWorkspace(); 40 view = factory.CreateView(); 41 } 42 43 abstract public void Dump(); 44 45 public void DumpState() 46 { 47 if (doc != null) doc.Dump(); 48 if (workspace != null) workspace.Dump(); 49 if (view != null) view.Dump(); 50 } 51 } 52 53 // These classes could be part of an application 54 class MyApplication : DPApplication 55 { 56 MyFactory myFactory = new MyFactory(); 57 58 override public void Dump() 59 { 60 Console.WriteLine("MyApplication exists"); 61 } 62 63 public void CreateFamily() 64 { 65 MyFactory myFactory = new MyFactory(); 66 ConstructObjects(myFactory); 67 } 68 } 69 70 class MyDocument : DPDocument 71 { 72 public MyDocument() 73 { 74 Console.WriteLine("in MyDocument constructor"); 75 } 76 77 override public void Dump() 78 { 79 Console.WriteLine("MyDocument exists"); 80 } 81 } 82 83 class MyWorkspace : DPWorkspace 84 { 85 override public void Dump() 86 { 87 Console.WriteLine("MyWorkspace exists"); 88 } 89 } 90 91 class MyView : DPView 92 { 93 override public void Dump() 94 { 95 Console.WriteLine("MyView exists"); 96 } 97 } 98 99 class MyFactory : DPFactory 100 { 101 override public DPDocument CreateDocument() 102 { 103 return new MyDocument(); 104 } 105 override public DPWorkspace CreateWorkspace() 106 { 107 return new MyWorkspace(); 108 } 109 override public DPView CreateView() 110 { 111 return new MyView(); 112 } 113 } 114 115 /// <summary> 116 /// Summary description for Client. 117 /// </summary> 118 public class Client 119 { 120 public static int Main(string[] args) 121 { 122 MyApplication myApplication = new MyApplication(); 123 124 myApplication.CreateFamily(); 125 126 myApplication.DumpState(); 127 128 return 0; 129 } 130 }
工厂模式
时间: 2024-10-13 11:01:11