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();
相关推荐
冬奇Lab7 分钟前
每日一个开源项目(第137篇):Penpot - 真正开源的设计协作工具,SVG 原生格式消灭设计-开发鸿沟
前端·开源·设计
nuIl24 分钟前
实现一个 Coding Agent(7):Skills
前端·agent·cursor
nuIl29 分钟前
实现一个 Coding Agent(8):会话持久化与多会话
前端·agent·cursor
jt君424262 小时前
React Native JSI 深入剖析 — 第 5 部分中文技术整理:用 HostObject 把 C++ 类暴露给 JavaScript
前端·react native
胡萝卜术2 小时前
滑动窗口最大值:从暴力到单调队列,层层优化全解析
前端·javascript·面试
fluffyox2 小时前
Notion 的公式栏里,藏着一台虚拟机——逆向 + 用 600 行 JS 复刻它的编译器与栈式 VM
前端
kyriewen3 小时前
2026 年了,这 6 个 npm 包可以卸载了——浏览器原生 API 已经能替代
前端·javascript·npm
铁皮饭盒4 小时前
bun直接tsx,优雅!
javascript·后端
Csvn5 小时前
Monorepo 迁移血泪史:从 Multi-Repo 到 Turborepo,这 3 个坑我帮你踩完了
前端
星栈6 小时前
Dioxus 多页面怎么做:`dioxus-router`、嵌套路由、`Outlet` 和页面组织,一篇给你讲顺
前端·rust·前端框架