设计模式系列:装饰模式

场景

早上饿了,我要煎饼果子。(我也是来了北京之后,知道早点还有煎饼果子,哈哈!)我对师傅说:师傅,来一套煎饼果子。(切克闹)师傅问:要加点啥?我瞅了瞅菜单,如下:

设计模式系列:装饰模式_第1张图片
煎饼果子图片.jpg

我说加个香肠和鸡蛋吧,师父说:好的。到算账的时候咋算呢?请实现此场景。

代码-version1

public class JbgzBuilder implements IBuilder {
    public JbgzFood build() {
        JbgzFood food = new JbgzFood();
        food.addStuff("面皮");
        food.addStuff("薄脆");
        food.addStuff("咸菜");
        food.addStuff("鸡蛋");
        return food;
    }
}

public class Test {
    public static void main(String[] args) {
       JbgzBuilder builder = new JbgzBuilder();
       builder.build();
    }
}

代码-version2

public class JbgzFood {
    private List stuffs = new ArrayList();
    public JbgzFood(){}
    public void addStuff(String stuff){
        stuffs.add(stuff);
    }
}

public class ChickenWillowBuilder implements IBuilder {
    private IBuilder builder;
    public ChickenWillowBuilder(IBuilder builder) {
        this.builder = builder;
    }
    public JbgzFood build() {
        JbgzFood food = builder.build();
        food.addStuff("chickenWillow");
        return food;
    }
}

public class EggBuilder implements IBuilder {
    private IBuilder builder;
    public EggBuilder(IBuilder builder) {
        this.builder = builder;
    }
    public JbgzFood build() {
        JbgzFood food =builder.build();
        food.addStuff("egg");
        return food;
    }
}

public class HamSausageBuilder implements IBuilder {
    private IBuilder builder;
    public HamSausageBuilder(IBuilder builder) {
        this.builder = builder;
    }
    public JbgzFood build() {
        JbgzFood food =builder.build();
        food.addStuff("hanSausage");
        return food;
    }
}

public class Test {
    public static void main(String[] args) {
        //基本煎饼果子,加鸡蛋,加鸡柳
        IBuilder eggCheckenBuilder = new ChickenWillowBuilder(new EggBuilder(new JbgzBuilder()));
        eggCheckenBuilder.build();
        //基本煎饼果子,加鸡蛋,加鸡柳,加火腿肠
        IBuilder builder = new HamSausageBuilder(new ChickenWillowBuilder(new EggBuilder(new JbgzBuilder())));
        builder.build();
    }
}

定义

动态给一个对象添加一些额外的职责,就象在墙上刷油漆.使用Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活。

其实这里的设计和IO流的功能叠加用的是同一种设计

类图

设计模式系列:装饰模式_第2张图片
装饰者.jpg

你可能感兴趣的:(设计模式系列:装饰模式)