JavaScript設計模式-- 簡單工廠(Factory)模式
定義: 使用一個類別生成各個不同實體, 這些實體都有相同介面, 因而能取得需要的實體。
e.g.
var Coffee = function() {
this.color = "brown";
};
var Milk = function() {
this.color = "white";
};
var OrangeJuice = function() {
this.color = "orange";
};
var DrinkShop = function() {
this.sellDrink = function(type) { // type: 判定傳入是何種飲料的字串
var drink;
if (typeof window[type] !== "function") { // 萬ㄧ都沒符合的字串, 就給預設值
type = "OrangeJuice";
}
drink = new window[type](); // 為了動態產生該種飲料的實體
drink.showColor = function() {
console.log("Drink color: " + drink.color);
};
return drink;
};
};
var drinkShop = new DrinkShop();
drinkShop.sellDrink("Milk").showColor(); // Drink color: white
// 如果再新增一種飲料也可以:
var Water = function() {
this.color = "transparent";
};
drinkShop.sellDrink("Water").showColor(); // Drink color: transparent
e.g.
var Coffee = function() {
this.color = "brown";
};
var Milk = function() {
this.color = "white";
};
var OrangeJuice = function() {
this.color = "orange";
};
var DrinkShop = function() {
this.sellDrink = function(type) { // type: 判定傳入是何種飲料的字串
var drink;
if (typeof window[type] !== "function") { // 萬ㄧ都沒符合的字串, 就給預設值
type = "OrangeJuice";
}
drink = new window[type](); // 為了動態產生該種飲料的實體
drink.showColor = function() {
console.log("Drink color: " + drink.color);
};
return drink;
};
};
var drinkShop = new DrinkShop();
drinkShop.sellDrink("Milk").showColor(); // Drink color: white
// 如果再新增一種飲料也可以:
var Water = function() {
this.color = "transparent";
};
drinkShop.sellDrink("Water").showColor(); // Drink color: transparent
留言
張貼留言