分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

js设计模式(一)---策略模式

发布时间:2023-09-06 01:23责任编辑:林大明关键词:js

策略模式:

定义:

  定义一系列的算法,把他们一个个封装起来,并且是他们可以相互替换

应用场景:

  要求实现某一个功能有多种方案可以选择。比如:条条大路通罗马

实现:

  场景,绩效为 S的人年终奖有 4倍工资,绩效为 A的人年终奖有 3倍工资,而绩效为 B的人年终奖是 2倍工资。假设财务部要求我们提供一段代码,来方便他们计算员工的年终奖。

var calculateBonus = function( performanceLevel, salary ){if ( performanceLevel === ‘S‘ ){return salary * 4;}if ( performanceLevel === ‘A‘ ){return salary * 3;}if ( performanceLevel === ‘B‘ ){return salary * 2;}};calculateBonus( ‘B‘, 20000 ); // 输出:40000calculateBonus( ‘S‘, 6000 ); // 输出:24000

但是这样简单的实现会造成,calculateBonus函数过于庞大、弹性差、复用性差

我们可以改进成

//定义解决方案var performanceS = function() {};performanceS.prototype.calculate = function(salary) { ???return salary * 4;};var performanceA = function() {};performanceA.prototype.calculate = function(salary) { ???return salary * 3;};var performanceB = function() {};performanceB.prototype.calculate = function(salary) { ???return salary * 2;};//定义奖金类 Bonus :var Bonus = function() { ???this.salary = null; // 原始工资 ???this.strategy = null; // 绩效等级对应的策略对象};Bonus.prototype.setSalary = function(salary) { ???this.salary = salary; // 设置员工的原始工资};Bonus.prototype.setStrategy = function(strategy) { ???this.strategy = strategy; // 设置员工绩效等级对应的策略对象};Bonus.prototype.getBonus = function() { // 取得奖金数额 ???return this.strategy.calculate(this.salary); // 把计算奖金的操作委托给对应的策略对象};//调用var bonus = new Bonus();bonus.setSalary( 10000 );bonus.setStrategy( new performanceS() ) ?//设置策略对象
console.log( bonus.getBonus() ); // 输出:40000

在js 中策略模式的使用

var strategies = { ???"S": function(salary) { ???????return salary * 4; ???}, ???"A": function(salary) { ???????return salary * 3; ???}, ???"B": function(salary) { ???????return salary * 2; ???}};var calculateBonus = function(level, salary) { ???return strategies[level](salary);};console.log(calculateBonus(‘S‘, 20000)); // 输出:80000console.log(calculateBonus(‘A‘, 10000)); // 输出:30000

js设计模式(一)---策略模式

原文地址:http://www.cnblogs.com/web-Rain/p/7803408.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved