본문 바로가기
SW 공부/Design Patterns

[디자인패턴] Decorator pattern (데코레이터 패턴)

by 꼬냉상 2022. 8. 28.

Purpose of Decorator Pattern (데코레이터 패턴의 목적)

- Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviors.
- 객체를 동적으로 래핑하여 기존 책임과 동작을 수정할 수 있습니다.

 

Design Principle (디자인원칙)

-  OCP (Open-Closed Principle) : easily extended to incorporate new behavior without modifying existing code

 

Decorator pattern (데코레이터 패턴)

- decoration은 '장식(포장)'이란 뜻 

- The Decorator Pattern attaches additional responsibilities to an object dynamically. (동적으로 추가 책임 할당)

- Decorators provide a flexible alternative to subclassing for extending functionality. (유연하게 기능 확장 가능)

- Key Mechanism :  composition and delegation 

- Decorator class mirrors the type of components they are decorating. 
   : 자기가 꾸미고자 하는 객체를 inheritance(상속) 받아 Decorator를 만들기 때문에, 동일한 type의 class를 부모로 삼으면 결국 type- hierarchy가 만들어져서 자식 Decorator가 pointing 할 수 있으므로 wrapped.. wrapped... 반복이 가능함

- Disadvantage : can generate a lot of small classes(e.g. Java I/O), hard to understand if not familiar with the pattern

  : 작은 클래스가 너무 많이 생성될 수 있고, 패턴에 익숙하지 않으면 이해가 어려움.

→ 기존에 구현되어 있는 클래스(둥근 모양의 빵)에 그때그때 필요한 기능(초콜릿, 치즈, 생크림)을 추가(장식, 포장)해나가는 설계 패턴으로 기능 확장이 필요할 때 상속의 대안으로 사용

 

Related Patterns

Adapter provides a different interface to its subject
- Proxy provides the same interface
Decorator provides an enhanced interface

 

Quiz) 아래 요구사항을 설계한 결과를 클래스 다이어그램으로 나타내시오. 단 HTML_Log 및 Encrypt_Log는 개별적으로 혹은 함께 어느 하나의 Logger에 적용될 수 있으며, Logger의 종류와 메시지를 가공하는 클래스의 종류도 향후 쉽 게 추가될 수 있어야 한다.

Logger의 종류에는 ConsoleLogger와 FileLogger가 있다. 이들은 모두 log(String msg)의 메쏘드를 구현하고 있다.
• 로깅되는 메시지를 HTML로 변환해주는 HTML_Log 클래스가 있으며 이 클래스는 makeHTML(String msg) 메쏘드를 제공한다.
• 로깅되는 메시지를 암호화해주는 Encrypt_Log 클래스가 있으며 이 클래스는 encrypt(String msg) 메쏘드를 제공한다.

 

Quiz) O/X 로 답하시오
- (X) Decorator (장식자)패턴은 객체의 생성을 추상화하는 패턴이다.

→ Decorator 패턴은 동적으로 추가 책임을 할당하는 구조적 패턴이다.

- (X) 장식자(Decorator) 패턴에서 ISP를 적용했기 때문에 새로운 장식자의 추가가 쉽다.

→ Decorator 패턴 OCP (Open-Closed Principle) 적용

 

Quiz) 다음 그림은 장식자(Decorator)패턴의 클래스 다이어그램을 나타낸다. Decorator 클래스에서 Component 클래스로 상속(inheritance)과 연관(association)관계가 함께 있는 이유에 대해 설명하시오.

→ Decorator 클래스가 decorate 하는 클래스와 동일한 부모 type 을 가져야만 , 여러 번 decorate 할 수 있다 .
decorated 된 인스턴스가 기존 Component 인스턴스 대신 쓰일 수 있도록 해야 한다.

 

 

본 글은 개인의 S/W 구조설계 역량 강화를 위한 학습 목적으로 정리된 내용입니다.
일부 타/개인 단체에 저작권이 있는 자료를 포함하고 있으므로, 절대 영리 목적으로 사용하실 수 없습니다.
반응형

댓글