装潢模式

装潢模式

我的理解是,装潢模式的作用就是:扩展类的功能但不修改类,也就是依赖倒置原则

用普通白饭和蛋炒饭举个例子

Food是他们都实现了的接口

public interface Food {
    double getPrice();
}

Rice(白饭)实现了Food接口

public class Rice implements Food {

    @Override
    public double getPrice() {
        return 2.0;
    }

}

蛋炒饭(EggRice)也实现了Food接口,并且持有一个实现了Food接口的对象,也就是普通白饭(EggRice装饰了Rice)

public class EggRice implements Food {

    private Food food;
    private double eggPrice = 1.0;

    public EggRice(Food food) {
        this.food = food;
    }

    @Override
    public double getPrice() {
        return food.getPrice() + eggPrice;
    }

}

测试类

public class Main {
    public static void main(String[] args) {

        Rice rice = new Rice();
        System.out.println("一碗饭要" + rice.getPrice() + "钱");
        EggRice eggRice = new EggRice(rice);
        System.out.println("一碗蛋炒饭要" + eggRice.getPrice() + "钱");
    }
}

输出结果是:

一碗饭要2.0钱
一碗蛋炒饭要3.0钱

posted @ 2018-01-03 22:47  shadow_demo  阅读(265)  评论(0)    收藏  举报