자바스크립트 장식자 패턴(Decorator pattern) 구현
Javascript 2012. 7. 3. 20:20
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)을 추가 시킨다.
-
// Decorator(장식자) 패턴
-
var Decorator = new (function () {
-
-
var Decorator = function () {
-
return this;
-
}
-
-
Decorator.fn = Decorator.prototype = {
-
-
add: function (obj, n, fn) {
-
-
obj[n] = function () { fn.apply(obj, Array.prototype.slice.call(arguments)); };
-
-
return this;
-
},
-
remove: function (obj, n) {
-
-
delete obj[n];
-
-
return this;
-
}
-
}
-
-
return Decorator;
-
-
} ())();
-
-
function obj1() {
-
return this;
-
}
-
-
obj1.prototype.msg = function (str) {
-
alert(str);
-
}
-
-
function obj2() {
-
return this;
-
}
-
-
obj2.prototype.method1 = function (str) {
-
alert(str);
-
}
-
-
function obj3() {
-
return this;
-
}
-
-
obj3.prototype.method1 = function (str) {
-
alert(str);
-
}
-
-
var obj1 = new obj1();
-
// add
-
Decorator.add(obj1, 'obj2_method1', new obj2().method1).add(obj1, 'obj3_method1', new obj3().method1);
-
// remove
-
//obj = Decorator.remove(obj1, 'obj3_method1');
-
-
obj1.msg('str1');
-
obj1.obj2_method1('str2');
-
obj1.obj3_method1('str3');