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();
相关推荐
拖拉斯旋风10 分钟前
防抖(Debounce)实战解析:如何用闭包优化频繁 AJAX 请求,提升用户体验
前端
老前端的功夫18 分钟前
TypeScript 全局类型声明:declare关键字的深度解析与实战
linux·前端·javascript·ubuntu·typescript·前端框架
golang学习记21 分钟前
VS Code 1.107 发布:AI 不再是插件,而是编辑器的「第一大脑」
前端
EndingCoder32 分钟前
TypeScript 入门:理解其本质与价值
前端·javascript·ubuntu·typescript·node.js
1024小神32 分钟前
cloudflare使用express实现api防止跨域cors
前端
we1less37 分钟前
[audio] AudioTrack (七) 播放流程分析
前端
2501_946244781 小时前
Flutter & OpenHarmony OA系统弹窗对话框组件开发指南
javascript·flutter·microsoft
Johnnyhaha1 小时前
Docker Compose Pull 超时与代理踩坑记录
前端
烟袅1 小时前
React 表单的控制欲:什么时候我们真得控制它了,什么时候该放养了?
前端·react.js
不想秃头的程序员1 小时前
吃透 JS 事件委托:从原理到实战,解锁高性能事件处理方案
前端·面试