概念
使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止.
代码编写
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);
}
}
}
}
主旨就是“你完不成就要找到你上司让他完成,你上次完不成就找上司的上司。。。”
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 设计模式学习-责任链模式
发表评论 取消回复