装饰者模式例子

装饰者模式例子

星巴兹咖啡代码

Beverage是个抽象类,有两个方法:setDescription()及cost()

public abstrace class Beverage{
    String description = "UnKnow Beverage";

    //setDescription()已经在此类实现了,但是cost()必须在子类实现
    public String getDescription(){
        return description();
    }

    public abstrace double cost();
}

然后实现Condiment(调料)抽象类,也就是装饰者类

public abstract class CondimentDecorator extends Beverage{
    //所有的调料都必须重新实现setDescription()方法
    public abstract String getDescription();
}

写饮料代码

//让Espresso扩展自Becerage类,因为Espresso是一种饮料
public class Espresso(){

    //为了设置饮料的描述,写一个构造器
    public Espresso(){
        description = "Espresso";
    }

    //计算Espresso的价钱,直接把Espresso的价格返回
    public double cost(){
        return 1.99;
    }
}

还有一种饮料HouseBlend和Espresso饮料是一样的。

写调料代码

//摩卡是一个装饰者,所以让它继承自CondimentDecorator ,CondimentDecorator 扩展自Beverage
public class Mocha extends CondimentDecorator {
    Beverage beverage;

    public Mocha(Beverage beverage){
        this.beverage = becerage;
    }

    public String getDescription(){
        return beverage.getDescription() + ",Mocha";
    }

    public double cost(){
        return 0.20 + beverage.cost();
    }

}

还有2种调料一样

测试代码

public class StarbuzzCoffee{
    public static void main(String[] args){
        Beverage beverage = new Espresso();
    System.out.println(beverage.getDescription() + "$" + beverage.cost());  

    //制造出一个DarkRoast对象
    Beverage beverage2 = new DrkRoast();
    //用Mocha装饰它
    beverage2 = new Mocha(beverage2);
    //用第二个Mocha装饰它
    beverage2 = new Mocha(beverage2);
    //用Whip装饰它
    beverage2 = new Whip(beverage2);
    System.out.println(berverage2.getDescription() + "$" + beverage2.cost);

    Beverage beverage3 = new HouseBlend();
    beverage3 = new Soy(beverage3);
    beverage3 = new Mocha(beverage3);
    beverage3 = new Whip(beverage3);
    System.out.println(berverage3.getDescription() + "$" + beverage3.cost);
    }           
}

你可能感兴趣的:(装饰者模式例子)