디자인 패턴
데코레이터 패턴, Decorator Pattern Java로 구현
ted k
2022. 7. 25. 18:23
데코레이터 패턴, Decorator Pattern
- 장식과 실제 내용물을 동일시
- 객체에 동적으로 책임을 추가
- 상속을 사용하지 않고 기능의 유연한 확장이 가능한 패턴
- 객체에 동적으로 새로운 서비스를 추가 할 수 있음
- 전체가 아닌 개별적인 객체에 새로운 기능을 추가 할 수 있음
- Component : 동적으로 추가할 서비스를 가질 수 있는 객체 정의
- ConcreteComponent : 추가적인 서비스가 필요한 실제 객체
- Decorator : Component의 참조자를 관리하면서 Component에 정의된 인터페이스를 만족하도록 정의
- ConcreteDecorator : 새롭게 추가되는 서비스를 실제 구현한 클래스로 addBehavior()를 구현한다.
결론
- 단순한 상속보다 설계의 융통성을 증대
- Decorator의 조합을 통해 새로운 서비스를 지속적으로 추가할 수 있음
- 필요없는 경우 Decorator를 삭제할 수 있음
- Decorator와 실제 컴포넌트는 동일한 것이 아님
- 작은 규모의 객체들이 많이 생성될 수 있음
- 자바의 I/O 스트림 클래스는 Decorator 패턴임
구현
package decorator;
abstract class Americano {
String productName = "Americano";
public String getName() {
return productName;
}
}
class Kenya extends Americano{
public String getName() {
productName = "Kenya" + productName;
return productName;
}
}
class Ethiopia extends Americano {
public String getName() {
productName = "Ethiopia" + productName;
return productName;
}
}
abstract class Decorations extends Americano {
Americano americano;
public Decorations(Americano americano) {
this.americano = americano;
}
public abstract String getName();
}
class Milk extends Decorations{
String name = "Milk";
public Milk(Americano americano) {
super(americano);
}
public String getName() {
return americano.getName() + " adding " + name;
}
}
class MochaSyrup extends Decorations {
String name = "Mocha Syrup ";
public MochaSyrup(Americano americano) {
super(americano);
}
public String getName() {
return americano.getName() + " adding " + name;
}
}
class WhippedCream extends Decorations {
String name = "Whipped Cream";
public WhippedCream(Americano americano) {
super(americano);
}
public String getName() {
return americano.getName() + " adding " + name;
}
}
public class DecoratorPattern {
public static void main(String[] args) {
Kenya k = new Kenya();
Ethiopia e = new Ethiopia();
Milk m = new Milk(k);
WhippedCream wc = new WhippedCream(m);
MochaSyrup ms = new MochaSyrup(m);
System.out.println(ms.getName());
}
}