装饰器模式

package decorateDesignMode;


public class TestDecorate02 {

    public static void main(String[] args) {

        Drink coffee=new Coffee();
        System.out.println(coffee.info()+coffee.cost());

        Drink milkCoffee=new Milk(coffee);
        System.out.println(milkCoffee.info()+milkCoffee.cost());

        Drink sugerMilkCoffee=new Suger(milkCoffee);
        System.out.println(sugerMilkCoffee.info()+sugerMilkCoffee.cost());

    }
}

/**
 * 抽象组件
 */
interface Drink{

    double cost();
    String info();

}

/**
 * 具体组件
 */
class Coffee implements Drink{

    private String name="乞力马扎罗";
    @Override
    public double cost() {
        return 20;
    }

    @Override
    public String info() {
        return this.name;
    }
}

/**
 * 抽象装饰类
 */

abstract class Decorate implements Drink {

    //抽象组件的引用
    private Drink drink;

    public Decorate(Drink drink) {
        this.drink = drink;
    }

    @Override
    public double cost() {
        return this.drink.cost();
    }

    @Override
    public String info() {
        return this.drink.info();
    }
}

/**
 * 具体装饰类
 */
class Milk extends Decorate{

    public Milk(Drink drink) {
        super(drink);
    }

    @Override
    public double cost() {
        return super.cost()*4;
    }

    @Override
    public String info() {
        return super.info()+"加了牛奶";
    }
}

/**
 * 具体装饰类
 */
class Suger extends Decorate{

    public Suger(Drink drink) {
        super(drink);
    }

    @Override
    public double cost() {
        return super.cost()*2;
    }

    @Override
    public String info() {
        return super.info()+"加了阿尔卑斯上特产甘泉糖";
    }
}



你可能感兴趣的:(java,设计模式)