目录

裴先生
裴先生
发布于 2022-04-09 / 0 阅读
0
0

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

原创
为了避免请求发送者与多个请求处理者耦合在一起,于是将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链;当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。
/**
 * 责任链抽象父类
 */
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.

原创

版权声明:本博客原创文章,由 裴先生 2022年04月09日 发表。
转载说明:除特殊说明外本站文章皆由 CC BY-NC-SA 4.0 协议发布,转载须注明出处。


评论