設計模式(裝飾模式)
阿新 • • 發佈:2018-12-24
父類(飲料,價格)
public abstract class Beverage {//飲料
public abstract String getDescription();
public abstract double cost();
}
子類(咖啡的)
public class Coffee extends Beverage{
@Override
public String getDescription() {
// TODO Auto-generated method stub
return “咖啡”;
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 10;
}
}
//子類(裝飾類)
public abstract class CondimentDecorator extends Beverage {
private Beverage beverage;
public CondimentDecorator(Beverage beverage) {
this.beverage = beverage;
}
public String getDescription() {
return this.beverage.getDescription();
}
public double cost() {
return this.beverage.cost();
}
}
//子類(牛奶)
public class Milk extends CondimentDecorator {
public Milk(Beverage beverage) {
super(beverage);
// TODO Auto-generated constructor stub
}
public String milk() {
return “牛奶”;
}
public double milkcost() {
return 2;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return super.getDescription()+ “+” + milk();
}
@Override
public double cost() {
// TODO Auto-generated method stub
return super.cost()+milkcost();
}
}
//子類(奶泡)
public class Whip extends CondimentDecorator{
public Whip(Beverage beverage) {
super(beverage);
// TODO Auto-generated constructor stub
}
public String milk() {
return “奶泡”;
}
public double milkcost() {
return 3;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return super.getDescription()+"+"+milk();
}
@Override
public double cost() {
// TODO Auto-generated method stub
return super.cost()+milkcost();
}
}
//測試類
public class Test {
public static void main(String[] args) {
Beverage coffee=new Coffee();
coffee=new Milk(coffee);
coffee=new Whip(coffee);
coffee=new Milk(coffee);
System.out.println(coffee.getDescription()+"$"+coffee.cost());
}
}