本文主要是介绍设计模式学习-责任链模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
概念
使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止.
代码编写
using UnityEngine;
using System.Collections;
public class ChainOfResponsbilityStucture :MonoBehaviour{void Start{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 };foreach (int request in requests){h1.HandleRequest(request);}}//声明一个抽象类规范子类的行为abstract class Handler{protected Handler successour;public void SetSuccessour(Handler successour){this.successour= successour;}public void abstract RequestHandler(int request);}public class ConcreteHandler1:Handler{public override void RequestHandler(int request){if(request>=0 &&request < 10){Debug.Log($"交给我处理{this.GetType().Name}handled request {request}");}else if(successour != null){successor.RequestHandler(request);}}}public class ConcreteHandler2:Handler{public override void RequestHandler(int request){if(request>=10 &&request < 20){Debug.Log($"交给我处理{this.GetType().Name}handled request {request}");}else if(successour != null){successor.RequestHandler(request);}}}public class ConcreteHandler3:Handler{public override void RequestHandler(int request){if(request>=20 &&request < 50){Debug.Log($"交给我处理{this.GetType().Name}handled request {request}");}else if(successour != null){successor.RequestHandler(request);}}}
}
主旨就是“你完不成就要找到你上司让他完成,你上次完不成就找上司的上司。。。”
这篇关于设计模式学习-责任链模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!