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();
相关推荐
zhensherlock14 小时前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
多加点辣也没关系16 小时前
JavaScript|第40章:JavaScript 工程化实践
开发语言·javascript·ecmascript
彩虹暴龙兽18 小时前
JavaScript 预编译机制与执行上下文构建分析
javascript
tryCbest19 小时前
Vue3——第 22 篇:Pinia——新一代状态管理(上)
前端·javascript·vue.js
bai27319 小时前
"👨‍👩‍👧‍👦" 的 length 是 11:我把自己写的字数统计脚本拖出来审了一遍
前端·javascript
bai27319 小时前
同一个 1.005,toFixed 给 1.00、Math.round 给 1、Intl 给 1.01:999 个三分位小数的实测
javascript·后端
爱编程的1719 小时前
一篇讲透 JS 对象:数据类型、原型链与包装类
javascript
zhanlang021720 小时前
HTML 零基础入门到企业实战【第八章 8.5】画布 canvas、SVG 矢量图形基础入门
前端·html
星云_byto21 小时前
CSS面试题
前端·css
zhanlang021721 小时前
HTML 零基础入门到企业实战全套教程【连载 8.4】HTML5 新增表单属性与表单控件
前端·html·html5