Unity实现设计模式——责任链模式
责任链模式定义:将请求的发送和接收解耦,让多个接收对象都有机会处理这个请求。将这些接收对象串成一条链,并沿着这条链传递这个请求,直到链上的某个接收对象能够处理它为止。
在职责链模式中,多个处理器(也就是刚刚定义中说的“接收对象”)依次处理同一个请求。一个请求先经过A处理器处理,然后再把请求传递给B处理器,B处理器处理完后再传递给C处理器,以此类推,形成一个链条。链条上的每个处理器各自承担各自的处理职责,所以叫作职责链模式。
这里使用管理者、副总裁、总裁、依次采购商品的例子
管理者可以去采购商品,当采购的数量大于某个阈值时管理者不能完成该任务需要上级去完成,当上级也完不成的时候就要向最上级报告处理请求了
1.Approver 管理者的基类
abstract class Approver
{
protected Approver successor;
public void SetSuccessor(Approver successor)
{
this.successor = successor;
}
public abstract void ProcessRequest(Purchase purchase);
}
2.Director 管理者
class Director : Approver
{
public override void ProcessRequest(Purchase purchase)
{
if (purchase.Amount < 10000.0)
{
Debug.Log(this.GetType().Name+" approved request# "+purchase.Number);
}
else if (successor != null)
{
successor.ProcessRequest(purchase);
}
}
}
3.VicePresident 副总裁
class VicePresident : Approver
{
public override void ProcessRequest(Purchase purchase)
{
if (purchase.Amount < 25000.0)
{
Debug.Log(this.GetType().Name + " approved request# " + purchase.Number);
}
else if (successor != null)
{
successor.ProcessRequest(purchase);
}
}
}
4.President 总裁
class President : Approver
{
public override void ProcessRequest(Purchase purchase)
{
if (purchase.Amount < 100000.0)
{
Debug.Log(this.GetType().Name + " approved request# " + purchase.Number);
}
else
{
Debug.Log("Request# "+purchase.Number+ "requires an executive meeting!");
}
}
}
5.Purchase 采购的商品
class Purchase
{
private int _number;
private double _amount;
private string _purpose;
// Constructor
public Purchase(int number, double amount, string purpose)
{
this._number = number;
this._amount = amount;
this._purpose = purpose;
}
// Gets or sets purchase number
public int Number
{
get { return _number; }
set { _number = value; }
}
// Gets or sets purchase amount
public double Amount
{
get { return _amount; }
set { _amount = value; }
}
// Gets or sets purchase purpose
public string Purpose
{
get { return _purpose; }
set { _purpose = value; }
}
}
6.测试
public class ChainOfResponsibilityExample1 : MonoBehaviour
{
void Start ( )
{
// Setup Chain of Responsibility
Approver larry = new Director();
Approver sam = new VicePresident();
Approver tammy = new President();
larry.SetSuccessor(sam);
sam.SetSuccessor(tammy);
// Generate and process purchase requests
Purchase p = new Purchase(2034, 350.00, "Assets");
larry.ProcessRequest(p);
p = new Purchase(2035, 32590.10, "Project X");
larry.ProcessRequest(p);
p = new Purchase(2036, 122100.00, "Project Y");
larry.ProcessRequest(p);
}
}