js模式之策略模式

ini 复制代码
//普通用户
function Price(){
    this.discount = 1
}
Price.prototype.getPrice = function(price){
    return price * this.discount
}
//vip用户
function VipPrice(){
    this.discount = 0.5
}
VipPrice.prototype.getPrice = function(price){
    return price * this.discount
}
//超级VIP用户
function SuperVipPrice(){
    this.discount = 0.3
}
SuperVipPrice.prototype.getPrice = function(price){
    return price * this.discount
}

//上下文
function Context(){
    this.name="";
    this.strategy=null;
    this.price=0
}
Context.prototype.set=function(name,strategy,price){
    this.name=name;
    this.strategy=strategy;
    this.price=price;
}
Context.prototype.getResult=function(){
    console.log(this.name+"的价格是:"+this.strategy.getPrice(this.price))
}
let context = new Context();
let price = new Price();
context.set("普通用户",price,200);
context.getResult();
let vipPrice = new VipPrice();
context.set("vip用户",vipPrice,200);
context.getResult();
let superVipPrice = new SuperVipPrice();
context.set("超级vip用户",superVipPrice,200);
context.getResult();
相关推荐
excel3 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel4 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼5 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping5 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙6 小时前
[译] Composition in CSS
前端·css
白水清风6 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix7 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278007 小时前
new、原型和原型链浅析
前端·javascript
阿星做前端7 小时前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧7 小时前
Promise 的使用
前端·javascript