자바스크립트 장식자 패턴(Decorator pattern) 구현



Decorator(장식자) Pattern

- 런타임 시 해당 객체에 원하는 기능(메서드)을 추가하는 패턴.

장식자 패턴은 더글라스 아저씨가 만드신 method() 함수에서도 찾아 볼 수 있다.


- javascript decorator pattern:

http://lostechies.com/jimmybogard/2009/01/20/javascript-decorator-pattern/


- 자바스크립트 method() 함수:

http://mohwaproject.tistory.com/archive/201202?page=2



아래 코드는 런타임 시 해당 객체(obj1)에 원하는 기능(method1, method2)을 추가 시킨다.


  1. // Decorator(장식자) 패턴
  2. var Decorator = new (function () {
  3.  
  4.     var Decorator = function () {
  5.         return this;
  6.     }
  7.  
  8.     Decorator.fn = Decorator.prototype = {
  9.  
  10.         add: function (obj, n, fn) {
  11.  
  12.             obj[n] = function () { fn.apply(obj, Array.prototype.slice.call(arguments)); };
  13.  
  14.             return this;
  15.         },
  16.         remove: function (obj, n) {
  17.  
  18.             delete obj[n];
  19.  
  20.             return this;
  21.         }
  22.     }
  23.  
  24.     return Decorator;
  25.  
  26. } ())();
  27.  
  28. function obj1() {
  29.     return this;
  30. }
  31.  
  32. obj1.prototype.msg = function (str) {
  33.     alert(str);
  34. }
  35.  
  36. function obj2() {
  37.     return this;
  38. }
  39.  
  40. obj2.prototype.method1 = function (str) {
  41.     alert(str);
  42. }
  43.  
  44. function obj3() {
  45.     return this;
  46. }
  47.  
  48. obj3.prototype.method1 = function (str) {
  49.     alert(str);
  50. }
  51.  
  52. var obj1 = new obj1();
  53. // add
  54. Decorator.add(obj1, 'obj2_method1', new obj2().method1).add(obj1, 'obj3_method1', new obj3().method1);
  55. // remove
  56. //obj = Decorator.remove(obj1, 'obj3_method1');
  57.  
  58. obj1.msg('str1');
  59. obj1.obj2_method1('str2');
  60. obj1.obj3_method1('str3');