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();
相关推荐
PineappleCoder6 分钟前
别让页面 “鬼畜跳”!Google 钦点的 3 个性能指标,治好了我 80% 的用户投诉
前端·性能优化
卤代烃20 分钟前
🕹️ [AI] Chrome DevTools MCP 原理分析
前端·mcp
梦里不知身是客1132 分钟前
flink对于迟到数据的处理
前端·javascript·flink
卤代烃43 分钟前
🤝 了解 CDP (Chrome DevTools Protocol):browser-use 背后的隐藏功臣
前端·chrome·puppeteer
一 乐1 小时前
人事管理系统|基于Springboot+vue的企业人力资源管理系统设计与实现(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot·后端
b***74881 小时前
前端状态系统的时代变革:从本地状态到全局状态,再到智能状态的未来趋势
前端·状态模式
秋氘渔1 小时前
Vue 3 组合式API中的生命周期钩子函数介绍
前端·javascript·vue.js
拉不动的猪1 小时前
requestAnimationFrame 与 JS 事件循环:宏任务执行顺序分析
前端·javascript·面试
步步为营DotNet1 小时前
深度解析C# 11的Required成员:编译期验证保障数据完整性
java·前端·c#
han_1 小时前
开发提效利器 - 用好Snippets
前端·javascript·visual studio code