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();
相关推荐
珎珎啊4 分钟前
前端-闭包
前端
军军君016 分钟前
数字孪生监控大屏实战模板:交通云实时数据监控平台
前端·javascript·css·vue.js·typescript·前端框架·echarts
不才小强12 分钟前
行为型设计模式
设计模式
DanCheOo17 分钟前
从脚本到 CLI 工具:用 Node.js 打造你的第一个 AI 命令行工具
前端·aigc
木斯佳17 分钟前
前端八股文面经大全:腾讯PCG前端暑期二战一面·深度解析(2026-04-22)·面经深度解析
前端·面经·实习
十一.36619 分钟前
012-014 对state的理解,初始化state,react中的事件绑定
前端·react.js·前端框架
你脸上有BUG19 分钟前
SSE库选型+fetch-event-source示例
前端·sse·通知订阅
Never_every9921 分钟前
8 个高清 4K 视频素材网址!无水印可商用
大数据·前端·音视频·视频
NotFound48624 分钟前
分享实战中Python Web 框架对比:Django vs Flask vs FastAPI
前端·python·django
冰暮流星24 分钟前
javascript之表单事件1
开发语言·前端·javascript