示例参考
/**
* 仓库
*/
class Stock {
constructor () {
if (Stock.instance)
return Stock.instance;
else
Stock.instance = this;
this.sum = 0;
this.list = [];
this.maxId = 0;
}
/**
* 入库
* @param {Product} product
*/
input (product) {
product.id = this.generateId();
this.sum += product.price;
this.list.push(product);
}
/**
* 出库
* @param {number} id
* @return {boolean}
*/
output (id) {
// 通过id找索引
let index = this.list.findIndex(it => {
return it.id === id;
});
if (index == -1)
return false;
// 减去总价
this.sum -= this.list[ index ].price;
// 删除产品
this.list.splice(index, 1);
}
/**
* 获取商品总价
* @return {number}
*/
getSum () {
return this.sum;
}
/**
* 获取商品总数
* @return {number}
*/
getTotal () {
return this.list.length;
}
/**
* 生成id
* @return {number}
*/
generateId () {
return ++this.maxId;
}
/**
* 获取所有商品
* @return {Array}
*/
all () {
return this.list;
}
}
/**
* 产品
*/
class Product {
constructor (type, price) {
this.type = type;
this.price = price;
}
}
let p1 = new Product('phone', 100);
let p2 = new Product('phone', 200);
let p3 = new Product('phone', 300);
let c1 = new Product('computer', 300);
let stock = new Stock();
stock.input(p1);
stock.input(p2);
stock.input(p3);
stock.input(c1);
console.log(stock.getSum());
console.log(stock.getTotal());
let stock2 = new Stock();
console.log(stock2 === stock);
stock2.output(2);
console.log(stock.getSum());
console.log(stock.getTotal());
console.log(stock.all());
登录后评论