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();
相关推荐
sunbyte19 分钟前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | VerifyAccountUi(验证码组件)
前端·javascript·css·vue.js·vue
yinuo21 分钟前
企业微信侧边栏本地开发调试
前端
GDAL27 分钟前
nest generate从入门到实战
javascript·nestjs·generate
德育处主任29 分钟前
p5.js 加载 3D 模型(loadModel)
前端·数据可视化·canvas
程序员爱钓鱼1 小时前
Go语言实战:图的邻接表表示法实现详解
javascript·后端·go
无名客02 小时前
npm run dev 启动项目 报Error: listen EACCES: permission denied 0.0.0.0:80 解决方法
前端·javascript·vue.js
零点七九2 小时前
vue npm install卡住没反应
前端·vue.js·npm
墨菲安全2 小时前
NPM组件 @0xme5war/apicli 等窃取主机敏感信息
前端·npm·node.js·主机信息窃取·npm恶意包·npm投毒
Komorebi_99992 小时前
vue create 项目名 和 npm init vue@latest 创建vue项目的不同
前端·vue.js·npm
好好研究5 小时前
使用JavaScript实现轮播图的自动切换和左右箭头切换效果
开发语言·前端·javascript·css·html