1 개요[ | ]
- decorator pattern
- 데코레이터 패턴, 장식자 패턴
- "장식과 내용물을 동일시한다."
- 동적으로 상황에 따라 어떤 객체에 책임을 덧붙이는 패턴
- 기능 확장이 필요할 때 상속의 대안이 될 수 있다.
- 책임과 행위를 변경하기 위해 동적으로 포장(wrapping)할 수 있다.
- 예시: java.io에 있는 InputStream, Reader, OutputStream, Writer
- 적용사례: 스크롤바
2 예제[ | ]
Java
Copy
abstract class Coffee {
public abstract double getCost();
public abstract String getIngredients();
}
class SimpleCoffee extends Coffee {
public double getCost() { return 1; }
public String getIngredients() { return "Coffee"; }
}
abstract class CoffeeDecorator extends Coffee {
protected final Coffee decoratedCoffee;
protected String ingredientSeparator = ", ";
public CoffeeDecorator(Coffee decoratedCoffee) {
this.decoratedCoffee = decoratedCoffee;
}
public double getCost() {
return decoratedCoffee.getCost();
}
public String getIngredients() {
return decoratedCoffee.getIngredients();
}
}
class Milk extends CoffeeDecorator {
public Milk(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.5;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Milk";
}
}
class WhipCoffee extends CoffeeDecorator {
public WhipCoffee(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.7;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Whip";
}
}
public class Main {
public static final void main(String[] args) {
Coffee c = new SimpleCoffee();
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
c = new Milk(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
c = new WhipCoffee(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
}
}
- 실행결과
text
Copy
Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 2.2; Ingredients: Coffee, Milk, Whip
3 같이 보기[ | ]
4 참고[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.