动态的给一个对象添加一些额外的功能
示例代码:
package com.dector;
public class Main {
public static void main(String[] args) {
Beverage b1 =new Soy(new Milk(new HouseBlend()));
System.out.println(b1.getDescription()+":"+b1.cost());
Beverage b2 = new Soy(new Mocha(new Milk(new HouseBlend())));
System.out.println(b2.getDescription()+":"+b2.cost());
}
}
package com.dector;
public abstract class Beverage {
String description = "unknow";
public String getDescription()
{
return this.description;
}
public abstract double cost();
}
class HouseBlend extends Beverage{
public String getDescription()
{
return "HouseBlend";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 1.0;
}
}
class DarkRoast extends Beverage{
public String getDescription()
{
return "DarkRoast";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 2.0;
}
}
abstract class CondimentDecorator extends Beverage{
Beverage bev;
}
class Milk extends CondimentDecorator{
private double money = 3.0;
public String getDescription()
{
return "MIlk "+ bev.getDescription();
}
public Milk(Beverage b){
this.bev = b;
}
@Override
public double cost() {
// TODO Auto-generated method stub
return this.money + bev.cost();
}
}
class Mocha extends CondimentDecorator{
private double money = 4.0;
public String getDescription()
{
return "Mocha "+ bev.getDescription();
}
public Mocha(Beverage b){
this.bev = b;
}
@Override
public double cost() {
// TODO Auto-generated method stub
return this.money + bev.cost();
}
}
class Soy extends CondimentDecorator{
private double money = 5.0;
public String getDescription()
{
return "Soy "+ bev.getDescription();
}
public Soy(Beverage b){
this.bev = b;
}
@Override
public double cost() {
// TODO Auto-generated method stub
return this.money + bev.cost();
}
}