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();
相关推荐
Jerry6 分钟前
Compose 从 View 系统迁移
前端
IT码农-爱吃辣条21 分钟前
Three.js 初级教程大全
开发语言·javascript·three.js
GIS之路26 分钟前
2025年 两院院士 增选有效候选人名单公布
前端
四岁半儿28 分钟前
vue,H5车牌弹框定制键盘包括新能源车牌
前端·vue.js
烛阴41 分钟前
告别繁琐的类型注解:TypeScript 类型推断完全指南
前端·javascript·typescript
gnip1 小时前
工程项目中.env 文件原理
前端·javascript
JefferyXZF1 小时前
Next.js Server Actions 详解: 无缝衔接前后端的革命性技术(八)
前端·全栈·next.js
JohnYan2 小时前
工作笔记 - CentOS7环境运行Bun应用
javascript·后端·容器
芜青2 小时前
HTML+CSS:浮动详解
前端·css·html
SchuylerEX3 小时前
第六章 JavaScript 互操(2).NET调用JS
前端·c#·.net·blazor·ui框架