//策略模式,和状态模式有点像
//状态模式的各方法通常是不可互相替代的,比如游戏中走和跳的方法
//策略模式的方法通常是独立可互相替代的,比如促销活动的打一折和打五折
//由于这时可能一次只需要一个方法,状态模式会造成代码冗余,推荐策略模式
var Stragtegy = function(){
//内部算法对象
var Stragtegy = {
price1: function(price){
console.log('一折');
},
price5: function(price){
console.log('五折');
}
};
return {
user: function(algorithm, price){
return Stragtegy[algorithm] && Stragtegy[algorithm](price);
},
//扩展方法的接口
add: function(type, fn){
Stragtegy[type] = fn;
}
}
}()
Stragtegy.user('price1', null);
Stragtegy.add('price7', function(){
console.log('七折');
});
Stragtegy.user('price7', null);