职责链模式实例

这是一个请求处理1,2,3的故事

//抽象处理类
using UnityEngine;

public abstract class AResponde {

    private AResponde up;
    private string type;

    public AResponde(string t)
    {
        type = t;
    }

    public void SetUp(AResponde r)
    {
        up = r;
    }

    public void HandleRequest(int num)
    {
        if (Handle(num))
        {
            Debug.Log(type + "处理了");
        }
        else {
            if (up != null)
            {
                up.HandleRequest(num);
            }
            else {
                Debug.Log("无法处理");
            }
        }
    }

    //私有的处理方法
    protected abstract bool Handle(int num);
}
//具体处理类1,2和3类似处理的2、3
public class OneResponde : AResponde {

    public OneResponde(string t):base(t){ }

    protected override bool Handle(int num)
    {
        //一顿操作
        if (num == 1) return true;

        return false;
    }
}
//使用测试
using UnityEngine;

public class testZRL : MonoBehaviour {
    
	void Start () {
        OneResponde one = new OneResponde("one");
        TwoResponde two = new TwoResponde("two");
        ThereResponde there = new ThereResponde("three");

        there.SetUp(two);
        two.SetUp(one);

        there.HandleRequest(1);
        there.HandleRequest(2);
        there.HandleRequest(3);
        there.HandleRequest(10);
    }
}


全程主要在于抽象的处理类的处理请求方法,他负责关注当前处理类能不能完成处理,如果不能就请由上级进行处理,直到有一个处理类能够处理或则不能处理了。


首页 我的博客
粤ICP备17103704号