概念

使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止.

代码编写
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);
			}
		}
	}
}

主旨就是“你完不成就要找到你上司让他完成,你上次完不成就找上司的上司。。。”

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部