Design pattern responsibility chain pattern

The responsibility chain pattern creates a chain of receiver objects for the request. This pattern gives the type of request and decouples the sender and receiver of the request. This type of design pattern belongs to behavioral pattern.

In this pattern, each recipient usually contains a reference to another recipient. If an object cannot process the request, it passes the same request to the next recipient, and so on.

It is hereby recorded that this mode has recently been used in the company's O2O project to dispatch orders according to routing rules.

Here is a simple logic implementation

 1  public abstract class RouteBase
 2 {
 3         private RouteBase _NextRoute = null;
 4         public void SetNextRoute(RouteBase routeBase)
 5         {
 6             _NextRoute = routeBase;
 7         }
 8         public abstract bool Route();
 9         /// <summary>
10         /// Routing rules
11         /// </summary>
12         public void RouteLink()
13         {
14             if (Route())
15             {
16                 return;
17             }
18             else
19             {
20                 _NextRoute.RouteLink();
21             }
22         }
23 }
Responsibility chain abstract base class
1  public class SaleRoute : RouteBase
2  {
3         public override bool Route()
4         {
5             Console.WriteLine("A");
6             // The processing logic finally determines whether to skip to the next rule processing
7             return false;
8         }
9 }
Concrete realization
1  public class StockRoute : RouteBase
2 {
3         public override bool Route()
4         {
5             Console.WriteLine("b");
6             // The processing logic finally determines whether to skip to the next rule processing
7             return true;
8         }
9  }
Concrete realization
1  RouteBase a = new SaleRoute();
2  RouteBase b = new StockRoute();
3  a.SetNextRoute(b);
4  a.RouteLink();
5 
6   Console.Read();
Client call

When using, we should be flexible. We can change the structure of the code according to the business requirements. We can also set the Routelink() method to be abstract and let the subclasses implement their own rules.

Keywords: PHP

Added by ssmK on Thu, 31 Oct 2019 16:30:42 +0200