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();
相关推荐
phdsky31 分钟前
【设计模式】建造者模式
c++·设计模式·建造者模式
小毛驴85037 分钟前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
o***Z44839 分钟前
前端性能优化案例
前端
张拭心42 分钟前
前端没有实际的必要了?结合今年工作内容,谈谈我的看法
前端·ai编程
姜太小白1 小时前
【前端】CSS媒体查询响应式设计详解:@media (max-width: 600px) {……}
前端·css·媒体
weixin_411191841 小时前
flutter中WebView的使用及JavaScript桥接的问题记录
javascript·flutter
HIT_Weston1 小时前
39、【Ubuntu】【远程开发】拉出内网 Web 服务:构建静态网页(二)
linux·前端·ubuntu
百***06011 小时前
SpringMVC 请求参数接收
前端·javascript·算法
天外天-亮1 小时前
Vue + excel下载 + 水印
前端·vue.js·excel
起个名字逛街玩1 小时前
前端正在走向“工程系统化”:从页面开发到复杂产品架构的深度进化
前端·架构