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();
相关推荐
嚴寒10 小时前
2025最终!Mac配置Flutter全平台开发环境完整指南(亲测有效)
前端·flutter
hi大雄10 小时前
如何用Claude Code 生成顶级UI ❇️
前端
拖拉斯旋风10 小时前
深入理解 CSS 选择器的底层逻辑:从层叠到优先级的本质
前端·css
半桶水专家10 小时前
npm run 的工作原理和工作流程
前端·npm·node.js
北辰浮光10 小时前
npm install core-js不成功
前端·javascript·npm
东华帝君11 小时前
React源码解读
前端
雾迟sec11 小时前
Web安全-文件上传漏洞-黑白名单及其它绕过思路(附思维导图)
javascript·安全·web安全·网络安全·apache·安全威胁分析
Mintopia11 小时前
🌱 AIGC 技术的轻量化趋势:Web 端“小而美”模型的崛起
前端·javascript·aigc
开发者小天11 小时前
React中的useRef的用法
开发语言·前端·javascript·react.js
im_AMBER11 小时前
React 11 登录页项目框架搭建
前端·学习·react.js·前端框架