首页 > 代码库 > 职责链模式、桥接模式
职责链模式、桥接模式
参考资料《大话设计模式》
职责链模式:
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(); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。