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();
相关推荐
合作小小程序员小小店17 小时前
web开发,在线%超市销售%管理系统,基于idea,html,jsp,java,ssh,sql server数据库。
java·前端·sqlserver·ssh·intellij-idea
不爱学英文的码字机器18 小时前
重塑 Web 性能:用 Rust 与 WASM 构建“零开销”图像处理器
前端·rust·wasm
浩星18 小时前
react的框架UmiJs(五米)
前端·javascript·react.js
o0向阳而生0o19 小时前
112、23种设计模式之命令模式(20/23)
设计模式·命令模式
将编程培养成爱好20 小时前
C++ 设计模式《外卖骑手状态系统》
c++·ui·设计模式·状态模式
猿太极20 小时前
设计模式学习(3)-行为型模式
c++·设计模式
子醉20 小时前
推荐一种适合前端开发使用的解决本地跨域问题的办法
前端
Niyy_20 小时前
前端一个工程构建多个项目,记录一次工程搭建
前端·javascript
xiangxiongfly91521 小时前
CSS link标签
前端·css
快乐非自愿1 天前
常用设计模式:工厂方法模式
javascript·设计模式·工厂方法模式