当前位置: 移动技术网 > IT编程>开发语言>JavaScript > javascript设计模式 – 策略模式原理与用法实例分析

javascript设计模式 – 策略模式原理与用法实例分析

2020年05月11日  | 移动技术网IT编程  | 我要评论

本文实例讲述了javascript设计模式 – 策略模式原理与用法。分享给大家供大家参考,具体如下:

介绍:策略模式中可以定义一些独立的类来封装不同的算法,每一个类封装一种具体的算法。在这里,每一种算法的封装都可以称之为一种策略。策略模式的主要目的是将算法的定义与使用分开。

定义:定义一系列算法类,将每一个算法封装起来,并让它们可以相互替换。策略模式让算法独立与使用它的客户而变化,也称为政策模式。策略模式是一种对象行为型模式。

场景:使用策略模式实现一个加减乘除的工具类,将四个算法进行封装。

示例:

var addstrategy = function(){
  this.caculate = function(num1, num2){
    return num1 + num2;
  }
}
 
var substrategy = function(){
  this.caculate = function(num1, num2){
    return num1 - num2;
  }
}
 
var mulstrategy = function(){
  this.caculate = function(num1, num2){
    return num1 * num2;
  }
}
 
var divstrategy = function(){
  this.caculate = function(num1, num2){
    return num1 / num2;
  }
}
 
var context = function(strategy){
  var _strategy = strategy;
 
  this.executestrategy = function(num1, num2){
    return _strategy.caculate(num1, num2)
  }
}
var add = new context(new addstrategy());
var sub = new context(new substrategy());
var mul = new context(new mulstrategy());
var div = new context(new divstrategy());
 
console.log('1 + 2 = ' + add.executestrategy(1, 2));
console.log('5 - 1 = ' + sub.executestrategy(5, 1));
console.log('3 * 2 = ' + mul.executestrategy(3, 2));
console.log('8 / 2 = ' + div.executestrategy(8, 2));
 
// 1 + 2 = 3
// 5 - 1 = 4
// 3 * 2 = 6
// 8 / 2 = 4

在这个例子里,context称之为环境类,环境类是使用算法的角色,他在解决某个问题时可以采用多种策略。我们的例子里,根据传递的策略不同,导致context作出不同的处理方式。
divstrategy,mulstrategy,substrategy,addstrategy称为策略类,用来实现具体策略。

策略模式总结:

优点:

* 提供了开关原则的完美支持,可以再不修改原有系统基础上进行扩展
* 策略模式提供了一种可以替换继承关系的办法
* 使用策略模式可以避免多重条件选择语句。

缺点:

* 客户端必须知道所有的策略类,并自行选择需要使用哪一个策略
* 策略模式将造成系统产生很多策略类,任何细小的变化都导致系统需要新增一个新的策略类
* 客户端每次只能选择使用一个策略类

感兴趣的朋友可以使用在线html/css/javascript代码运行工具:测试上述代码运行效果。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网