자바스크립트 (Singleton, Factory, Chain, Interator) Pattern 구현
Javascript 2012. 7. 4. 18:15
Singleton Pattern
함수클래스의 객체를 단 "하나"만 생성하게 만드는 디자인 패턴.
즉, 동일한 함수클래스 호출 시 반환되는 두번째 객체 부터는 이전에 생성된 객체를 반환하게 된다.
-
var Singleton = (function () {
-
-
var that = null;
-
-
var Singleton = function () {
-
-
if (that) return that;
-
-
that = this;
-
-
return that;
-
}
-
-
return Singleton;
-
-
})();
-
-
function User() {
-
return this;
-
}
-
-
var obj1 = Singleton();
-
var obj2 = Singleton();
-
-
//alert(obj1 === obj2); // true
-
//alert(new User() === new User()); // false
Factory Pattern
사용자가 구체적인 클래스 정보를 모르고도 빌드(객체 생성 캡슐화)를 통해 객체를 생성할 수 있도록 만드는 디자인 패턴.
아래 코드에서는 클래스 타입 뿐 아니라 해당 클래스의 매개변수까지 넘겨 객체를 반환할 수 있게 설계 되었다.
-
var Factory = (function () {
-
-
var Factory = function () {
-
-
var ns = arguments[0].split('.')
-
, parent = eval(ns[0])
-
, childs = ns.slice(1);
-
-
for (var i = 0, length = childs.length; i < length; i++) {
-
-
if (!parent[childs[i]]) break;
-
-
parent = parent[childs[i]];
-
}
-
-
// parent.apply(obj, []) 함수의 반환값은 parent 함수(User)를 실행시킨 결과 return this(window object) 이다.
-
function T(args) { return parent.apply(this, Array.prototype.slice.call(args, 1)); };
-
-
T.prototype = parent.prototype;
-
-
return new T(arguments);
-
}
-
-
return Factory;
-
-
})();
-
-
-
function User(name, score) {
-
this.name = name;
-
this.score = score;
-
-
return this;
-
}
-
-
User.prototype.getName = function () {
-
return this.name;
-
}
-
-
User.prototype.getScore = function () {
-
return this.score;
-
}
-
-
User.name1 = function (name, score) {
-
this.name = name;
-
this.score = score;
-
return this;
-
}
-
-
User.name1.prototype.getName = function () {
-
return this.name;
-
}
-
-
User.name1.prototype.getScore = function () {
-
return this.score;
-
}
-
-
-
var obj1 = Factory('User', 'user1', 1);
-
var obj2 = Factory('User.name1', 'user2', 2);
-
-
alert(obj1.getName());
-
alert(obj1.getScore());
-
-
alert(obj2.getName());
-
alert(obj2.getScore());
Chain Pattern
해당 객체를 메서드의 반환 값으로 지정하여 연속된 메서드를 호출할 수 있도록 만드는 디자인 패턴이다.
-
var Chain = new (function () {
-
-
var Chain = function () {
-
-
this.name = '';
-
this.age = 0;
-
-
return this;
-
};
-
-
Chain.fn = Chain.prototype = {
-
-
getName: function () {
-
return this.name;
-
},
-
setName: function (name) {
-
this.name = name;
-
return this;
-
-
},
-
getAge: function () {
-
return this.age;
-
},
-
setAge: function (age) {
-
this.age = age;
-
return this;
-
}
-
};
-
-
return Chain;
-
-
}())();
-
-
//alert(Chain.setName('test').getName()); // test
-
//alert(Chain.setAge(10).getAge()); // 10
-
//alert(Chain.setName('test').setAge(10).getAge()); // 10
Interator(반복자) Pattern
기능의 세부적인 구현을 외부로 노출시키지 않고, 컨테이너(Interator(arguments)의 요소에 차례대로 접근할 수 있는 방법(.each())을 제공하는 디자인 패턴
-
var Interator = (function () {
-
-
var Interator = function () {
-
return new Interator.fn.init(arguments);
-
};
-
-
Interator.fn = Interator.prototype = {
-
init: function (arguments) {
-
this.arguments = arguments;
-
return this;
-
},
-
each: function (callback) {
-
-
callback = typeof callback === 'function' ? callback : function () { ; };
-
-
for (var i = 0, length = this.arguments.length; i < length; i++) {
-
-
var argument = this.arguments[i];
-
callback.call(argument, i);
-
}
-
}
-
};
-
-
Interator.fn.init.prototype = Interator.prototype;
-
-
return Interator;
-
-
})();
-
-
-
Interator(1, 2, 3).each(function (i) {
-
alert(this + ',' + i);
-
});