设计模式学习总结(十)责任链模式(Chain Of Responsibility)
责任链主要指通过一连串的操作来实现某项功能或者在处理相关的业务时,对于自己的业务则进行处理,反之,对于不属于自己的业务,则进行下发!
一、示例展示:
以下例子主要通过对煤矿对井下警告信息的处理来进行说明,如果瓦斯浓度超出一定范围值时,某个系统会自动发送短信到矿井的值班领导手机上,如果超出范围继续扩大,会向上一级继续发送,直到发送到矿领导的手机上!
1. 创建抽象处理者角色(Handler):Leader
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public abstract class Leader { protected string LeaderName; protected Leader leader; public Leader(string LeaderName) { this.LeaderName = LeaderName; } public void SetSuperiorLeader(Leader leader) { this.leader = leader; } abstract public void ProcessAlert(int AlertValue); }
2. 创建具体处理者角色(Concrete Handler): OnDutyLeader
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class OnDutyLeader : Leader { public OnDutyLeader(string LeaderName) : base(LeaderName) { } public override void ProcessAlert(int AlertValue) { if (AlertValue <= 10) { Console.WriteLine("Onduty leader is processing!"); } else { leader.ProcessAlert(AlertValue); } } }
3. 创建具体处理者角色(Concrete Handler): DepartmentLeader
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class DepartmentLeader : Leader { public DepartmentLeader(string LeaderName) : base(LeaderName) { } public override void ProcessAlert(int AlertValue) { if (AlertValue <= 30) { Console.WriteLine("Department leader is processing!"); } else { leader.ProcessAlert(AlertValue); } } }
4. 创建具体处理者角色(Concrete Handler): SuperLeader
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class SuperLeader : Leader { public SuperLeader(string LeaderName) : base(LeaderName) { } public override void ProcessAlert(int AlertValue) { Console.WriteLine("The super leader is processing!"); } }
5. 客户端调用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { OnDutyLeader leaderA = new OnDutyLeader("LeaderA"); DepartmentLeader leaderB = new DepartmentLeader("LeaderB"); SuperLeader leaderC = new SuperLeader("LeaderC"); leaderA.SetSuperiorLeader(leaderB); leaderB.SetSuperiorLeader(leaderC); leaderA.ProcessAlert(50); leaderA.ProcessAlert(30); leaderA.ProcessAlert(10); Console.ReadLine(); } }
二、策略模式设计理念:
通过抽象具体处理者的共同的方法与属性,形成了抽象处理者角色。根据已经创建的具体处理者对象,设置对象相互之间的依赖关系,进而将各个对象串联在整个责任链之上,达到逐级处理的目地!
三、角色及关系: