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();
相关推荐
xiaoyustudiowww1 分钟前
fetch异步简单版本(Tomcat 9)
java·前端·tomcat
TOPGUS2 分钟前
谷歌Chrome浏览器即将对HTTP网站设卡:突出展示“始终使用安全连接”功能
前端·网络·chrome·http·搜索引擎·seo·数字营销
C_心欲无痕9 分钟前
ts - 模板字面量类型与 `keyof` 的魔法组合:`keyof T & `on${string}`使用
linux·运维·开发语言·前端·ubuntu·typescript
Van_captain10 分钟前
rn_for_openharmony常用组件_Tabs选项卡
javascript·开源·harmonyos
赵民勇11 分钟前
ES6中的const用法详解
javascript·es6
一勺菠萝丶14 分钟前
Java 后端想学 Vue,又想写浏览器插件?
java·前端·vue.js
@PHARAOH19 分钟前
HOW - 如何禁用 localstorage
前端·状态模式
霍理迪19 分钟前
CSS布局方式——弹性盒子(flex)
前端·css
vx-bot55566626 分钟前
企业微信接口在自动化工作流中的关键角色与设计模式
设计模式·自动化·企业微信
Van_captain29 分钟前
React Native for OpenHarmony Toast 轻提示组件:自动消失的操作反馈
javascript·开源·harmonyos