데코레이터 패턴

1 개요[ | ]

decorator pattern
데코레이터 패턴, 장식자 패턴
  • "장식과 내용물을 동일시한다."
  • 동적으로 상황에 따라 어떤 객체에 책임을 덧붙이는 패턴
  • 기능 확장이 필요할 때 상속의 대안이 될 수 있다.
  • 책임과 행위를 변경하기 위해 동적으로 포장(wrapping)할 수 있다.
  • 예시: java.io에 있는 InputStream, Reader, OutputStream, Writer
  • 적용사례: 스크롤바

Decorator UML class diagram.svg

W3sDesign Decorator Design Pattern UML.jpg

2 예제[ | ]

  • Coffee : 추상적인 커피
  • CoffeeDecorator : 추상적인 커피 첨가물
  • SimpleCoffee : 그냥 커피
  • Milk : 우유[1]
  • Whip : 휘핑크림[2]
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());
	}
}
실행결과
Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 2.2; Ingredients: Coffee, Milk, Whip

3 같이 보기[ | ]

4 참고[ | ]

  1. 커피 첨가물이지만 커피 역할 가능
  2. 커피 첨가물이지만 커피 역할 가능
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}