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

219次阅读
一条评论

共计 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.
正文完
 
裴先生
版权声明:本站原创文章,由 裴先生 2022-04-09发表,共计2000字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(一条评论)
langhai 评论达人 LV.1
2024-02-05 22:25:47 回复

使用责任链设计模式,可以使请求的发送者和请求的接收处理者解耦,同时增强了给对象指派职责的灵活性。 :beer: 浪海导航 日常一游

     中国湖南省长沙市电信
本站勉强运行: