职责链模式 -- 大话设计模式
在今天,读书有时是件“麻烦”事。它需要你付出时间,付出精力,还要付出一份心境。--仅以《大话设计模式》来祭奠那逝去的……
职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传送请求,直到有一个对象处理它为止
1.我要加薪,经理同意了,老板不批
经理小A和Boss小B,员工小C向小A提出申请意向,小A提交加薪申请,具体谁负责批复,客户端不知道
定义一个申请类,不管是加薪还是请假
/// <summary> /// 申请类 /// </summary> public class Request { public string Type { get; set; } public string Content { get; set; } public int Number { get; set; } }
定义管理者抽象类和具体管理者经理和BOSS(注意为给个级别的管理者定义上级和提交申请的具体业务)
/// <summary> /// 管理者抽象类 /// </summary> public abstract class Manager { protected string Name { get; set; } public Manager(string name) { this.Name = name; } protected Manager superior; /// <summary> /// 设置管理者上级 /// </summary> public void SetSuperior(Manager superior) { this.superior = superior; } /// <summary> /// 申请请求 /// </summary> public abstract void RequestApplications(Request request); } /// <summary> /// 部门经理 /// </summary> public class CommonManager : Manager { public CommonManager(string name) : base(name) { } public override void RequestApplications(Request request) { if (request.Type == "加薪" && request.Number <= 500) { Console.WriteLine("{0}:{1} 数量{2} 被批准", this.Name, request.Content, request.Number); } else { if (this.superior != null) superior.RequestApplications(request); } } } /// <summary> /// 公司老板 /// </summary> public class BossManager : Manager { public BossManager(string name) : base(name) { } public override void RequestApplications(Request request) { if (request.Type == "加薪" && request.Number > 500 && request.Number < 1000) { Console.WriteLine("{0}:{1} 数量{2} 被批准", this.Name, request.Content, request.Number); } else { Console.WriteLine("{0}:{1} 数量{2} 被驳回", this.Name, request.Content, request.Number); } } }
开启场景模拟
static void Main(string[] args) { //经理小A和Boss小B CommonManager xiaoA = new CommonManager("小A"); BossManager xiaoB = new BossManager("小B"); //设置小A的上级 xiaoA.SetSuperior(xiaoB); //员工提出申请意向 Request request = new Request(); request.Type = "加薪"; request.Content = "员工小C提出加薪请求"; request.Number = 1000; //经理发起给小C加薪的申请,具体谁来处理客户端不知道 xiaoA.RequestApplications(request); }