關于單例及子產品模式,之前寫過一篇部落格 。
子產品模式傳回一個對象,這個對象有一些私有屬性和方法,并且提供了api來通路這些私有資料。
let singleton = function(){
//私有變量和函數
let privateVariable = 10;
function privateFunction(){
return false;
}
//特權方法和屬性
return {
publicProperty : true,
publicMethod: function(){
privateVariable++;
return privateFunction();
}
}
}();
下面使用子產品模式來實作一個簡單的購物車。
購物車就是一個子產品,商品資訊是購物車的私有資料,外部無法通路,我們需要提供一些方法來操作商品資訊。
let shoppingCart = function () {
let goodsList = [];
return {
addItem: (item) => {
goodsList.push(item);
},
removeItem: (index) => {
goodsList.splice(index, 1);
},
getCount: () => {
return goodsList.length;
},
getTotalPrice: () => {
let price = 0;
goodsList.forEach(item => {
price += item.price;
})
return price;
}
}
}();
shoppingCart.addItem({
name: 't-shirt',
price: 199
});
shoppingCart.addItem({
name: 'umbrella',
price: 45
});
shoppingCart.addItem({
name: 'shoes',
price: 365.9
});
console.log(shoppingCart.getCount());
console.log(shoppingCart.getTotalPrice());
shoppingCart.removeItem(1);
console.log(shoppingCart.getCount());
console.log(shoppingCart.getTotalPrice());