객체에 추가적인 책임을 동적으로 부여
상속을 사용하지 않아도 유연하고 융통성 있는 기능 확장을 가능하게 함
public abstract class Beverage {
private String description = "제목 없";
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public abstract double cost();
}
public class HouseBlend extends Beverage{
public HouseBlend() {
super.setDescription("하우스 블렌드 커피");
}
@Override
public double cost() {
return .89;
}
}
public abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();
}
public class Mocha extends CondimentDecorator{
private Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
@Override
public double cost() {
return beverage.cost() + .20;
}
@Override
public String getDescription() {
return beverage.getDescription() + ", 모카";
}
}
public class Main {
public static void main(String[] args) {
Beverage beverage = new HouseBlend();
beverage = new Mocha(beverage); // 데코레이터로 beverage 감싼다.
System.out.println(beverage.getDescription());
}
}