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();
相关推荐
Sheldon一蓑烟雨任平生16 分钟前
Sass 星空(Sass + keyframes 实现星空动画)
前端·css·vue3·sass·keyframes
⑩-23 分钟前
VUE3学习
前端·javascript·vue.js
Mr Xu_28 分钟前
Vue 3 中使用 mitt 实现组件间通信的实践与解析
前端·javascript·vue.js
呃m37 分钟前
更好地使用Google Chrome
前端·chrome
巧克力芋泥包37 分钟前
Vue3 详情页跨页循环(上一条,下一条)导航功能实现
前端·javascript·vue.js
摘星编程1 小时前
React Native + OpenHarmony:BottomSheet联动效果实现
javascript·react native·react.js
前端之虎陈随易1 小时前
前端通用插件开发工具unplugin v3.0.0发布
前端·typescript
老蒋每日coding1 小时前
AI Agent 设计模式系列(十四)—— 知识检索(RAG)模式
人工智能·设计模式·langchain
Ashley_Amanda1 小时前
SAP调用Web Service全流程详解
java·前端·数据库
Dreamy smile1 小时前
css :nth-child() 完全用法指南
前端·css