标签:style blog class c code java
参考资料《大话设计模式》
职责链模式:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ds_chainofresponsibility { class Program { static void Main(string[] args) { Handler h1 = new ConcreteHandler1(); Handler h2 = new ConcreteHandler2(); Handler h3 = new ConcreteHandler3(); h1.SetSuccessor(h2); h2.SetSuccessor(h3); int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 ,100 }; foreach (int request in requests) { h1.HandleRequest(request); } } } /// <summary> /// 处理请求的接口 /// </summary> abstract class Handler { protected Handler successor; public void SetSuccessor(Handler successor)//设置继任者 { this.successor = successor; } public abstract void HandleRequest(int request);//处理请求的抽象方法 } /// <summary> /// 处理0-10之间的请求 /// </summary> class ConcreteHandler1 : Handler { public override void HandleRequest(int request) { if (request >= 0 && request < 10) { Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request); } else if (successor != null) { successor.HandleRequest(request);//转移到下一位 } } } /// <summary> /// 处理10-20之间的请求 /// </summary> class ConcreteHandler2 : Handler { public override void HandleRequest(int request) { if (request >= 10 && request < 20) { Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request); } else if (successor != null) { successor.HandleRequest(request);//转移到下一位 } } } /// <summary> /// 处理20-30之间的请求 /// </summary> class ConcreteHandler3 : Handler { public override void HandleRequest(int request) { if (request >= 20 && request < 30) { Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request); } else if (successor != null) { successor.HandleRequest(request);//转移到下一位 } else { Console.WriteLine("不能处理请求{0}",request); } } } }
桥接模式:将抽象部分与实现部分分离。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ds_bridge { class Program { static void Main(string[] args) { Abstraction abs = new Abstraction(); abs.SetImplementor(new ConcreteImplementorA()); abs.Operation(); abs.SetImplementor(new ConcreteImplementorB()); abs.Operation(); /*Implementor ss = new ConcreteImplementorA(); ss.Operation();*/ } } /// <summary> /// 实现 /// </summary> abstract class Implementor { public abstract void Operation(); } /// <summary> /// 具体实现 /// </summary> class ConcreteImplementorA : Implementor { public override void Operation() { Console.WriteLine("具体实现A的方法执行"); } } class ConcreteImplementorB : Implementor { public override void Operation() { Console.WriteLine("具体实现B的方法执行"); } } /// <summary> /// 抽象 /// </summary> class Abstraction { protected Implementor implementor; public void SetImplementor(Implementor implementor) { this.implementor = implementor; } public virtual void Operation() { implementor.Operation(); } } class RefinedAbstraction : Abstraction { public override void Operation() { implementor.Operation(); } } }
标签:style blog class c code java
原文地址:http://www.cnblogs.com/nju347/p/3737571.html