본문 바로가기
Design Pattern/Structural Design

[Design Pattern] (Structural) 데코레이터 패턴(Decorator Pattern)

by song.ift 2023. 3. 27.

디자인 패턴 유형

  • Creation Design Pattern
    • 객체의 생성에 관련된 패턴
    • 객체의 생성 로직을 숨김으로써 유연성을 향상시킨다.
  • Strutural Design Pattern
    • 클래스와 객체의 구성에 관련된 패턴
  • Behavioral Design Pattern
    • 객체와 객체 간의 통신에 관련된 패턴

 

[Structural Design Pattern] 데코레이터 패턴(Decorator Pattern)

런타임시 객체에 동적으로 부가기능을 추가할 수 있는 패턴
Decorator 패턴의 예제는 아래와 같다.

javascript
닫기
var sale = new Sale(100); sale = sale.decorate('fedtax'); sale = sale.decorate('quebec'); sale = sale.decorate('money'); sale.getPrice(); // $112.88

구현 예제는 다음과 같다.

javascript
닫기
function Sale(price) { this.price = price || 100; } Sale.prototype.getPrice = function() { return this.price; } Sale.decorators = {}; Sale.decorators.fedtax = { getPrice: function() { ​​​​​​var price = this.uber.getPrice(); // uber 는 상속된 객체 ​​​​​​price += price * 5 / 100; // 5% 세율 추가 ​​​​​​ ​​​​​​return price; ​​​​} }; Sale.decorators.money = { getPrice: function() { ‌​​​​return '$' + this.uber.getPrice().toFixed(2); ​​​​} }

위 decorators()를 아래와 같이 구현할 수 있다.

javascript
닫기
Sale.prototype.decorate = function(decorators) { ​​var F = function() {}, ​​​​​​​​overrides = this.constructor.decorators[decorator], ​​​​​​​​i, newobj; ​​F.prototype = this; ​​newobj = new F(); ​​newobj.uber = F.prototype; ​​for (i in overrides) { ‌​​if (overrides.hasOwnProperty(i)) { ‌​​​​newobj[i] = overrides[i]; ​​​​} ​​} ​​return newobj; };

댓글