在
程序设计中,我们也
经常遇到这种
情况,要实现一定的
功能,我们有一些算法可以实现。
这些算法灵活多样,可以随意更换,这种
解决方案就是所谓的
策略模式。
策略模式被定义为一系列算法的定义,这些算法一个一个地封装它们,并允许它们相互
替换。
*
*前:Policy Pattern
例:
公司计算奖金,分为三种表现,A、B和C。计算
方法如下
*演出是A,奖金乘以系数5。
*表现是B,奖金乘以系数4。
*
性能是C,奖金乘以系数3。
* /
/ / --------示例1—
VAR将calculateBonus =功能(水平、工资){
如果(水平=){
回报工资* 5;
}
如果(水平= 'b'){
回报工资* 4;
}
如果(水平= C){
回报工资* 3;
}
};
console.log(将calculateBonus(A,2000));
*
缺点:1。
函数系统庞大,有太多的if语句。
2。如果性能d增加,则需要
修改内部函数并违反开闭原则。
3、重用性差等地方,如果用在计算奖金分配上只能
粘贴;
* /
/ / ---------示例2—
VAR绩效=功能(工资){
回报工资* 5;
};
无功performanceb =功能(工资){
回报工资* 4;
};
无功性能=功能(工资){
回报工资* 3;
};
VAR将calculateBonus =功能(水平、工资){
如果(水平=){
返回试验(工资);
}
如果(水平= 'b'){
返回performanceb(工资);
}
如果(水平= C){
返回性能(工资);
}
};
console.log(将calculateBonus(A,2000));
*
缺点:1。当系统发生变化时,系统功能庞大,系统缺乏弹性。
* /
/ / ---------示例3—
策略模型重构:定义一系列算法,每个算法都
打包在一起。
Var(绩效=功能){ };
performancea.prototype.caculate =功能(工资){
回报工资* 5;
};
Var(performanceb =功能){ };
performanceb.prototype.caculate =功能(工资){
回报工资* 4;
};
Var(性能=功能){ };
performancec.prototype.caculate =功能(工资){
回报工资* 3;
};
var =函数(){()
this.salary = null;
this.strategy = null;
};
bonus.prototype.setsalary =功能(工资){
this.salary =工资;
};
bonus.prototype.setstrategy =功能(策略){
this.strategy =战略;
}
bonus.prototype.getbonus =函数(){
返回this.strategy.caculate(这待遇。);
}
var奖金=新奖金();
(2000)bonus.setsalary;
Bonus.setStrategy(新性能A());
console.log(bonus.getbonus());
示例4 - —
版本
var策略= {
a:函数(工资){
回报工资* 5;
},
B:函数(工资){
回报工资* 4;
},
:函数(工资){
回报工资* 3;
}
};
无功caculatebonus =功能(水平、工资){
返回策略{ }(工资);
};
console.log(caculatebonus(
以上是本文的全部内容,希望能对您有所帮助,希望大家多多
支持。