Chain of Responsibility Pattern: Allows multiple objects to have the opportunity to process requests, thereby avoiding the coupling relationship between the sender and receiver of the request. These objects are connected into a chain and the request is passed along the chain until an object handles it.
The idea is very simple, for example, consider employees’ requests for a salary increase. There are three levels of managers in the company, general manager, director, and manager. If an employee requires a salary increase, he should apply to the manager in charge. If the amount of salary increase is within the manager's authority, the manager can directly approve it, otherwise the application will be made. Submit to the Director. The same goes for the Director, the General Manager can handle all requests. This is a typical chain of responsibility model. The processing of requests forms a chain until an object handles the request. A UML diagram is given for this example.
UML structure diagram:
##An example of the chain of responsibility model*This example is the situation of three types of salespersons processing orders
*If the order If the amount is less than 1,000, the first-level salesperson can process the order
*If the order amount is less than 10,000, the second-level salesperson can process the order
*If the order amount is less than 100,000, the third-level salesperson can process the order
using System; /**//// <summary> ///售货员接口,所有类型的售货员必须实现该接口 /// </summary> interface ISalesMan { string Name {set;get;} //售货员名字 void SetNext(ISalesMan nextSalesMan); //设置下一级售货员 void Process(Order order); //处理订单 } /**//// <summary> /// 订单类 /// </summary> class Order { private int orderAmount; public int Amount { set{ this.orderAmount = value;} get{ return this.orderAmount; } } } /**//// <summary> /// 一类售货员 /// </summary> class FirstSalesMan : ISalesMan { private ISalesMan nextSalesMan = null; private string name = string.Empty; ISalesMan 成员ISalesMan 成员 } /**//// <summary> /// 二类售货员 /// </summary> class SecondSalesMan : ISalesMan { private ISalesMan nextSalesMan = null; private string name = string.Empty; ISalesMan 成员ISalesMan 成员 } /**//// <summary> /// 三类售货员 /// </summary> class ThirdSalesMan : ISalesMan { private ISalesMan nextSalesMan = null; private string name = string.Empty; ISalesMan 成员ISalesMan 成员 } class Client { public static void Main(string[] args) { FirstSalesMan first = new FirstSalesMan(); first.Name = "firstMan"; SecondSalesMan second = new SecondSalesMan(); second.Name = "secondMan"; ThirdSalesMan third = new ThirdSalesMan(); third.Name = "thirdMan"; first.SetNext(second); second.SetNext(third); Order o = new Order(); o.Amount = 300; first.Process(o); o = new Order(); o.Amount = 1300; first.Process(o); o = new Order(); o.Amount = 11300; first.Process(o); Console.Read(); } }