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();
相关推荐
Ulyanov6 分钟前
打造现代化雷达电子对抗仿真界面 第二篇:雷达电子对抗仿真系统核心功能实现
前端·python·信息可视化·数据可视化·系统仿真·雷达电子战
鬣主任6 分钟前
重生之我上班学React----360档案篇。
javascript·react.js
快乐小土豆~~7 分钟前
上传视频时截取正脸照片
前端·音视频·vladmandic
276695829218 分钟前
token1005 算法分析
java·前端·javascript·token·token1005·携程酒店·token算法分析
乆夨(jiuze)18 分钟前
记录一个css,实现下划线内容显示,支持文本多行显示
前端·css
GISer_Jing20 分钟前
前端视频多模态:编解码、传输、渲染全链路详解
前端·人工智能·音视频
陌上丨24 分钟前
优雅终止线程的设计模式
设计模式
恋猫de小郭28 分钟前
Flutter PC 多窗口最新进展,底层原生窗口句柄支持已合并
android·前端·flutter
LIO41 分钟前
Vue3 + Vite + Pinia + TypeScript 项目完整搭建与实战指南
前端·vue.js
张涛酱10745642 分钟前
Agent Skills 深入解析:构建可插拔的智能体知识体系
spring·设计模式·ai编程