用简单代码初识责任链设计模式

  • A+
所属分类:JAVA


共计 2000 个字符,预计需要花费 5 分钟才能阅读完成。

为了避免请求发送者与多个请求处理者耦合在一起,于是将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链;当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。

/**
 * 责任链抽象父类
 */
public abstract class HandlerChain {
    /**
     * 责任链,下一步
     */
    protected HandlerChain nextHandlerChain;

    public void setNextHandlerChain(HandlerChain nextHandlerChain) {
        this.nextHandlerChain = nextHandlerChain;
    }

    /**
     * 做饭方法
     */
    public void cook() {
        // 做自己的事
        dealWith();
        if (nextHandlerChain != null) {
            nextHandlerChain.cook();
        }
    }

    /**
     * 处理自己该做的事
     */
    protected abstract void dealWith();
}

购买

/**
 * 购买食材处理类
 */
public class BuyIngredient extends HandlerChain{
    @Override
    protected void dealWith() {
        System.out.println("First, Buy ingredient Success.");
    }
}

清洗

/**
 * 清洗食材处理类
 */
public class WashIngredient extends HandlerChain{
    @Override
    protected void dealWith() {
        System.out.println("Second, Wash ingredient Success.");
    }
}

做食材

/**
 * 做食材处理类
 */
public class MakeIngredient extends HandlerChain{
    @Override
    protected void dealWith() {
        System.out.println("Third, Make ingredient Success.");
    }
}

吃食材

/**
 * 吃食材处理类
 */
public class EatIngredient extends HandlerChain{
    @Override
    protected void dealWith() {
        System.out.println("Fourth, Eat ingredient Success.");
    }
}

洗盘子

/**
 * 清洗盘子
 */
public class WashTheDishes extends HandlerChain{
    @Override
    protected void dealWith() {
        System.out.println("Final, Wash the dishes Success.");
    }
}
/**
 * 责任链测试类
 */
public class HandleChainDemo {
    public static void main(String[] args) {
        // 获取责任链
        BuyIngredient buyIngredient = getCookHandlerChain();
        // 执行cook方法
        buyIngredient.cook();
    }

    private static BuyIngredient getCookHandlerChain() {
        BuyIngredient buyIngredient = new BuyIngredient();
        WashIngredient washIngredient = new WashIngredient();
        MakeIngredient makeIngredient = new MakeIngredient();
        EatIngredient eatIngredient = new EatIngredient();
        WashTheDishes washTheDishes = new WashTheDishes();

        buyIngredient.setNextHandlerChain(washIngredient);
        washIngredient.setNextHandlerChain(makeIngredient);
        makeIngredient.setNextHandlerChain(eatIngredient);
        eatIngredient.setNextHandlerChain(washTheDishes);
        return buyIngredient;
    }
}
First, Buy ingredient Success.
Second, Wash ingredient Success.
Third, Make ingredient Success.
Fourth, Eat ingredient Success.
Final, Wash the dishes Success.
  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: