Javascript Patterns 7장 디자인 패턴
요약본입니다. 이번 포스팅의 경우 아키텍쳐 패턴이라기 보단, 자바스크립트에서 함수를 만드는 것에 있어서 디자인 패턴이라고 이해하면 좋을 것 같다. views의 비지니스 로직을 담아 놓은 controller나 store에서 메서드를 디자인 하는것에 참고하면 좋을 것 같다.
var obj = {
myprop : "my value"
};
var obj2 = {
myprop : "my value"
};
obj === obj2; // false
obj == obj2; // false
// 팩토리 패턴 구현 예제
function CarMaker() {}
CarMaker.prototype.drive = function () {
return "Vroom, I have " + this.doors + "doors";
};
CarMaker.factory = function (type) {
var constr = type,
newcar;
// 생성자 존재하지 않으면 에러발생
if (typeof CarMaker[constr] !== "function") {
throw {
name: "Error",
message: constr + "doesn't exist"
};
}
// 생성자 존재 확인 후 부모 상속
if (typeof CarMaker[constr].prototype.drive !== "function") {
CarMaker[constr].prototype = new CarMaker();
}
newcar = new CarMaker[constr]();
return newcar;
};
CarMaker.Compact = function () {
this.doors = 4;
};
CarMaker.Convertible = function () {
this.doors = 2;
};
CarMaker.SUV = function () {
this.doors = 24;
};
// --
// 위 패턴을 이용한 결과
var corolla = CarMaker.factory("Compact");
var solstice = CarMaker.factory("Convertible");
corolla.drive(); // "Vroom, I have 4 doors"
solstice.drive(); // "Vroom, I have 2 doors"
var agg = (function () {
var index = 0,
data = [1, 2, 3, 4, 5],
length = data.length;
return {
next : function () {
var element;
if (!this.hasNext()) {
return null;
}
element = data[index];
index += 1;
return element;
},
hasNext : function () {
return index < length;
},
rewind: function () {
index = 0;
},
current: function () {
return data[index];
}
};
}());
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);
}
};
var proxy = {
ids : [],
delay: 50,
timeout: null,
callback: null,
context: null,
makeRequest: function (id, callback, context) {
this.ids.push(id);
this.callback = callback;
this.context = context;
if (!this.timeout) {
this.timeout = setTimeout(function () {
proxy.flush();
}, this.delay);
}
},
flush: function () {
http.makeRequest(this.ids, "proxy.handler:");
this.timeout = null;
this.ids = [];
},
handler: function (data) {
var i, max;
if (parseInt(data.query.count, 10) === 1) {
proxy.callback.call(proxy.context, data.query.results.Video);
return;
}
for (i = 0, max = data.query.results.Video.length;
i < max; i += 1) {
proxy.callback.call(proxy.context, data.query.results.Video[i]);
}
}
};