[置顶]c# 设计模式(2)结构型
2011-07-14 17:38 乱世文章 阅读(174) 评论(0) 编辑 收藏 举报名称 | Adapter |
结构 | |
意图 | 将一个类的接口转换成客户希望的另外一个接口。A d a p t e r 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。 |
适用性 |
|
Code Example | namespace Adapter_DesignPattern { using System; class FrameworkXTarget { virtual public void SomeRequest(int x) { // normal implementation of SomeRequest goes here } } class FrameworkYAdaptee { public void QuiteADifferentRequest(string str) { Console.WriteLine("QuiteADifferentRequest = {0}", str); } } class OurAdapter : FrameworkXTarget { private FrameworkYAdaptee adaptee = new FrameworkYAdaptee(); override public void SomeRequest(int a) { string b; b = a.ToString(); adaptee.QuiteADifferentRequest(b); } } /// <summary> /// Summary description for Client. /// </summary> public class Client { void GenericClientCode(FrameworkXTarget x) { // We assume this function contains client-side code that only // knows about FrameworkXTarget. x.SomeRequest(4); // other calls to FrameworkX go here // ... } public static int Main(string[] args) { Client c = new Client(); FrameworkXTarget x = new OurAdapter(); c.GenericClientCode(x); return 0; } } } |
名称 | Bridge |
结构 | |
意图 | 将抽象部分与它的实现部分分离,使它们都可以独立地变化。 |
适用性 |
|
Code Example | namespace Bridge_DesignPattern { using System; class Abstraction { protected Implementation impToUse; public void SetImplementation(Implementation i) { impToUse = i; } virtual public void DumpString(string str) { impToUse.DoStringOp(str); } } class DerivedAbstraction_One : Abstraction { override public void DumpString(string str) { str += ".com"; impToUse.DoStringOp(str); } } class Implementation { public virtual void DoStringOp(string str) { Console.WriteLine("Standard implementation - print string as is"); Console.WriteLine("string = {0}", str); } } class DerivedImplementation_One : Implementation { override public void DoStringOp(string str) { Console.WriteLine("DerivedImplementation_One - don't print string"); } } class DerivedImplementation_Two : Implementation { override public void DoStringOp(string str) { Console.WriteLine("DerivedImplementation_Two - print string twice"); Console.WriteLine("string = {0}", str); Console.WriteLine("string = {0}", str); } } /// <summary> /// Summary description for Client. /// </summary> public class Client { Abstraction SetupMyParticularAbstraction() { // we localize to this method the decision which abstraction and // which implementation to use. These need to be decided // somewhere and we do it here. All teh rest of the client // code can work against the abstraction object. Abstraction a = new DerivedAbstraction_One(); a.SetImplementation(new DerivedImplementation_Two()); return a; } public static int Main(string[] args) { Client c = new Client(); Abstraction a = c.SetupMyParticularAbstraction(); // From here on client code thinks it is talking to the // abstraction, and will not need to be changed as // derived abstractions are changed. // more client code using the abstraction goes here // . . . a.DumpString("Clipcode"); return 0; } } } |
名称 | Composite |
结构 | |
意图 | 将对象组合成树形结构以表示“部分-整体”的层次结构。C o m p o s i t e 使得用户对单个对象和组合对象的使用具有一致性。 |
适用性 |
|
Code Example | namespace FactoryMethod_DesignPattern { using System; using System.Collections; abstract class Component { protected string strName; public Component(string name) { strName = name; } abstract public void Add(Component c); public abstract void DumpContents(); // other operations for delete, get, etc. } class Composite : Component { private ArrayList ComponentList = new ArrayList(); public Composite(string s) : base(s) {} override public void Add(Component c) { ComponentList.Add(c); } public override void DumpContents() { // First dump the name of this composite node Console.WriteLine("Node: {0}", strName); // Then loop through children, and get then to dump their contents foreach (Component c in ComponentList) { c.DumpContents(); } } } class Leaf : Component { public Leaf(string s) : base(s) {} override public void Add(Component c) { Console.WriteLine("Cannot add to a leaf"); } public override void DumpContents() { Console.WriteLine("Node: {0}", strName); } } /// <summary> /// Summary description for Client. /// </summary> public class Client { Component SetupTree() { // here we have to create a tree structure, // consisting of composites and leafs. Composite root = new Composite("root-composite"); Composite parentcomposite; Composite composite; Leaf leaf; parentcomposite = root; composite = new Composite("first level - first sibling - composite"); parentcomposite.Add(composite); leaf = new Leaf("first level - second sibling - leaf"); parentcomposite.Add(leaf); parentcomposite = composite; composite = new Composite("second level - first sibling - composite"); parentcomposite.Add(composite); composite = new Composite("second level - second sibling - composite"); parentcomposite.Add(composite); // we will leaf the second level - first sibling empty, and start // populating the second level - second sibling parentcomposite = composite; leaf = new Leaf("third level - first sibling - leaf"); parentcomposite.Add(leaf); leaf = new Leaf("third level - second sibling - leaf"); parentcomposite.Add(leaf); composite = new Composite("third level - third sibling - composite"); parentcomposite.Add(composite); return root; } public static int Main(string[] args) { Component component; Client c = new Client(); component = c.SetupTree(); component.DumpContents(); return 0; } } } |
名称 | Decorator |
结构 | |
意图 | 动态地给一个对象添加一些额外的职责。就增加功能来说,D e c o r a t o r 模式相比生成子类更为灵活。 |
适用性 |
|
Code Example | namespace Decorator_DesignPattern { using System; abstract class Component { public abstract void Draw(); } class ConcreteComponent : Component { private string strName; public ConcreteComponent(string s) { strName = s; } public override void Draw() { Console.WriteLine("ConcreteComponent - {0}", strName); } } abstract class Decorator : Component { protected Component ActualComponent; public void SetComponent(Component c) { ActualComponent = c; } public override void Draw() { if (ActualComponent != null) ActualComponent.Draw(); } } class ConcreteDecorator : Decorator { private string strDecoratorName; public ConcreteDecorator (string str) { // how decoration occurs is localized inside this decorator // For this demo, we simply print a decorator name strDecoratorName = str; } public override void Draw() { CustomDecoration(); base.Draw(); } void CustomDecoration() { Console.WriteLine("In ConcreteDecorator: decoration goes here"); Console.WriteLine("{0}", strDecoratorName); } } /// <summary> /// Summary description for Client. /// </summary> public class Client { Component Setup() { ConcreteComponent c = new ConcreteComponent("This is the real component"); ConcreteDecorator d = new ConcreteDecorator("This is a decorator for the component"); d.SetComponent(c); return d; } public static int Main(string[] args) { Client client = new Client(); Component c = client.Setup(); // The code below will work equally well with the real component, // or a decorator for the component c.Draw(); return 0; } } } |
名称 | Facade |
结构 | |
意图 | 为子系统中的一组接口提供一个一致的界面,F a c a d e 模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。 |
适用性 |
|
Code Example | namespace Facade_DesignPattern { using System; class SubSystem_class1 { public void OperationX() { Console.WriteLine("SubSystem_class1.OperationX called"); } } class SubSystem_class2 { public void OperationY() { Console.WriteLine("SubSystem_class2.OperationY called"); } } class SubSystem_class3 { public void OperationZ() { Console.WriteLine("SubSystem_class3.OperationZ called"); } } class Facade { private SubSystem_class1 c1 = new SubSystem_class1(); private SubSystem_class2 c2 = new SubSystem_class2(); private SubSystem_class3 c3 = new SubSystem_class3(); public void OperationWrapper() { Console.WriteLine("The Facade OperationWrapper carries out complex decision-making"); Console.WriteLine("which in turn results in calls to the subsystem classes"); c1.OperationX(); if (1==1 /*some really complex decision*/) { c2.OperationY(); } // lots of complex code here . . . c3.OperationZ(); } } /// <summary> /// Summary description for Client. /// </summary> public class Client { public static int Main(string[] args) { Facade facade = new Facade(); Console.WriteLine("Client calls the Facade OperationWrapper"); facade.OperationWrapper(); return 0; } } } |
名称 | Flyweight |
结构 | |
意图 | 运用共享技术有效地支持大量细粒度的对象。 |
适用性 |
|
Code Example | namespace Flyweight_DesignPattern { using System; using System.Collections; class FlyweightFactory { private ArrayList pool = new ArrayList(); // the flyweightfactory can crete all entries in the pool at startup // (if the pool is small, and it is likely all will be used), or as // needed, if the pool si large and it is likely some will never be used public FlyweightFactory() { pool.Add(new ConcreteEvenFlyweight()); pool.Add(new ConcreteUnevenFlyweight()); } public Flyweight GetFlyweight(int key) { // here we would determine if the flyweight identified by key // exists, and if so return it. If not, we would create it. // As in this demo we have implementation all the possible // flyweights we wish to use, we retrun the suitable one. int i = key % 2; return((Flyweight)pool[i]); } } abstract class Flyweight { abstract public void DoOperation(int extrinsicState); } class UnsharedConcreteFlyweight : Flyweight { override public void DoOperation(int extrinsicState) { } } class ConcreteEvenFlyweight : Flyweight { override public void DoOperation(int extrinsicState) { Console.WriteLine("In ConcreteEvenFlyweight.DoOperation: {0}", extrinsicState); } } class ConcreteUnevenFlyweight : Flyweight { override public void DoOperation(int extrinsicState) { Console.WriteLine("In ConcreteUnevenFlyweight.DoOperation: {0}", extrinsicState); } } /// <summary> /// Summary description for Client. /// </summary> public class Client { public static int Main(string[] args) { int[] data = {1,2,3,4,5,6,7,8}; FlyweightFactory f = new FlyweightFactory(); int extrinsicState = 3; foreach (int i in data) { Flyweight flyweight = f.GetFlyweight(i); flyweight.DoOperation(extrinsicState); } return 0; } } } |
名称 | Proxy |
结构 | |
意图 | 为其他对象提供一种代理以控制对这个对象的访问。 |
适用性 |
|
Code Example | namespace Proxy_DesignPattern { using System; using System.Threading; /// <summary> /// Summary description for Client. /// </summary> abstract class CommonSubject { abstract public void Request(); } class ActualSubject : CommonSubject { public ActualSubject() { // Assume constructor here does some operation that takes quite a // while - hence the need for a proxy - to delay incurring this // delay until (and if) the actual subject is needed Console.WriteLine("Starting to construct ActualSubject"); Thread.Sleep(1000); // represents lots of processing! Console.WriteLine("Finished constructing ActualSubject"); } override public void Request() { Console.WriteLine("Executing request in ActualSubject"); } } class Proxy : CommonSubject { ActualSubject actualSubject; override public void Request() { if (actualSubject == null) actualSubject = new ActualSubject(); actualSubject.Request(); } } public class Client { public static int Main(string[] args) { Proxy p = new Proxy(); // Perform actions here // . . . if (1==1) // at some later point, based on a condition, p.Request();// we determine if we need to use subject return 0; } } }
|