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();
相关推荐
dy171738 分钟前
el-table表头上下显示内容
javascript·vue.js·elementui
q***649739 分钟前
头歌答案--爬虫实战
java·前端·爬虫
凌波粒40 分钟前
SpringMVC基础教程(4)--Ajax/拦截器/文件上传和下载
java·前端·spring·ajax
亮子AI1 小时前
给你的应用加上Google账号登录
javascript
液态不合群1 小时前
DDD驱动低代码开发:从业务流程到领域模型的全链路设计
前端·低代码·架构·ddd
jonyleek1 小时前
JVS低代码开发中,如何创建自定义前端页面并接入到现有系统中,从创建到接入的全攻略
前端·低代码·前端框架·软件开发
努力往上爬de蜗牛2 小时前
react native 实现选择图片或者拍照上传(多张)
javascript·react native·react.js
谢尔登2 小时前
【React】React组件的渲染过程分为哪几个阶段?
前端·javascript·react.js
MediaTea2 小时前
Python 第三方库:Flask(轻量级 Web 框架)
开发语言·前端·后端·python·flask
5***o5002 小时前
前端构建工具缓存清理,解决依赖问题
前端·缓存