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();
相关推荐
hssfscv3 分钟前
软件设计师2021上、下上午题错题解析+2022上、下下午题训练5道 练习真题训练16
笔记·设计模式·uml
GuWenyue19 分钟前
我被 React 性能问题逼疯了,直到学会这 4 个优化技巧
前端
窗边的anini29 分钟前
那个因为 vibecoding 差点搞砸约会的女孩,被 TRAE SOLO 救了
前端·人工智能·程序员
用户7138742290030 分钟前
OAuth 2.0 client_id深度解析:从规范到安全实践
前端
李燚33 分钟前
ReAct 循环的 50 行 Go 实现,逐行拆解
javascript·人工智能·react.js·golang·aigc·agent
ZC跨境爬虫36 分钟前
跟着 MDN 学CSS day_8:(盒模型完全解)
前端·javascript·css·ui·交互
Cache技术分享37 分钟前
415. Java 文件操作基础 - 精准读取压缩诗集:从二进制文件中高效提取指定十四行诗
前端·后端
光影少年38 分钟前
react自定义Hook 写法、规则(只能在组件/自定义Hook内调用)
前端·react.js·掘金·金石计划
JieE21240 分钟前
手把手带你用虚拟头节点实现单链表,搞定所有边界问题
javascript·算法
风骏时光牛马1 小时前
C语言核心高频问题与代码实战梳理
前端