본문 바로가기
Theory/Design Pattern

Decorator Pattern

by y.j 2022. 5. 8.
728x90

Decorator Pattern

추가적인 기능을 object에 유동적으로 부여하는 것이다. subclassing이나 상속의 유동적 대안책으로 사용된다.

어떻게 object에 추가적인 책임을 유동적으로 부여 할 수 있을까?
어떻게 object의 기능을 run-time에 확장시킬 수 있을까?

이 Pattern은 상속처럼 compile-time에 클래스의 기능을 확장하는 것을 회피하기 위해서 사용된다. 예를 들어 web application에서는 버튼이나 스크롤의 이벤트에 따라 기능이 추가될 수도 있다. 이럴 경우 run-time에 기능을 추가하는 것이 필요한데 Decorator Pattern으로 해결이 가능하다.

Solution

Component에 기본적인 함수를 정의를 해놓고 Component를 상속받는다. Component를 상속받은 decorator는 Component에 기본적인 기능을 수행하면서 추가적인 기능(addBehavior 함수)으로 감싸 줄 수 있도록 한다.

public class Decorator1 extends Decorator {
    private DecoratorComponent component;

    public Decorator1(DecoratorComponent component) {
        super(component);
    }

    @Override
    public String operation() {
        String result = super.operation();
        return addBehavior(result);
    }

    private String addBehavior(String result) {
        return "***" + result + "***";
    }
}

Advantages

• subclassing에 유동적 대안책이 된다.

• 다른 decorator와 협동함으로써 기능을 결합하기 쉽다.

• Allows an open-ended number of added functionalities.

• decorator는 decorated object를 모두 들여다 볼 수 있어 재귀적으로 충첨될 수 있다.

   따라서, 추가적인 기능을 무제한으로 생성할 수 있다.

• Client입장에서는 decorator통해서 작동하는지 직접적으로 작동하는지 알 필요가 없다.

• class들을 단순하게 한다.

  - 모든 특징들을 지원하는 클래스를 만드는 것 대신에 점진적으로 기능을 추가하거나 클래스를 정의할 수 있다.

 

Disadvantages
• decorator object는 모두 들여다 볼수 있지만, identity를 가지지 않는다.

  그러므로, identity를 가지는 application에서는 사용 할 수 없다.

728x90

'Theory > Design Pattern' 카테고리의 다른 글

Flyweight Pattern  (0) 2022.05.09
Facade Pattern  (0) 2022.05.09
Composite Pattern  (0) 2022.05.05
Proxy Pattern  (0) 2022.04.24
Bridge Pattern  (0) 2022.04.24

댓글