(笔记)设计模式 - 行为型模式1:策略模式、模板方法模式

原贴:http://blog.csdn.net/zhangerqing/article/details/8243942java

## 策略模式(strategy)算法

策略模式定义了一系列算法,并将每一个算法封装起来,使他们能够相互替换,且算法的变化不会影响到使用算法的客户。须要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(无关紧要,属于辅助类),提供辅助函数。ide

策略模式的决定权在用户,系统自己提供不一样算法的实现,新增或者删除算法,对各类算法作封装。所以,策略模式多用在算法决策系统中,外部用户只须要决定用哪一个算法便可。函数

图中ICalculator提供赞成的方法,
AbstractCalculator是辅助类,提供辅助方法,接下来,依次实现下每一个类:测试

首先统一接口:.net

[java] view plain copy设计

  1. public interface ICalculator {  
  2.     public int calculate(String exp);  
  3. }  

辅助类:blog

[java] view plain copy继承

  1. public abstract class AbstractCalculator {  
  2.       
  3.     public int[] split(String exp,String opt){  
  4.         String array[] = exp.split(opt);  
  5.         int arrayInt[] = new int[2];  
  6.         arrayInt[0] = Integer.parseInt(array[0]);  
  7.         arrayInt[1] = Integer.parseInt(array[1]);  
  8.         return arrayInt;  
  9.     }  
  10. }  

三个实现类:接口

[java] view plain copy

  1. public class Plus extends AbstractCalculator implements ICalculator {  
  2.   
  3.     @Override  
  4.     public int calculate(String exp) {  
  5.         int arrayInt[] = split(exp,"\\+");  
  6.         return arrayInt[0]+arrayInt[1];  
  7.     }  
  8. }  

[java] view plain copy

  1. public class Minus extends AbstractCalculator implements ICalculator {  
  2.   
  3.     @Override  
  4.     public int calculate(String exp) {  
  5.         int arrayInt[] = split(exp,"-");  
  6.         return arrayInt[0]-arrayInt[1];  
  7.     }  
  8.   
  9. }  

[java] view plain copy

  1. public class Multiply extends AbstractCalculator implements ICalculator {  
  2.   
  3.     @Override  
  4.     public int calculate(String exp) {  
  5.         int arrayInt[] = split(exp,"\\*");  
  6.         return arrayInt[0]*arrayInt[1];  
  7.     }  
  8. }  

简单的测试类:

[java] view plain copy

  1. public class StrategyTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         String exp = "2+8";  
  5.         ICalculator cal = new Plus();  
  6.         int result = cal.calculate(exp);  
  7.         System.out.println(result);  
  8.     }  
  9. }  

输出:10

策略模式的决定权在用户,系统自己提供不一样算法的实现,新增或者删除算法,对各类算法作封装。所以,策略模式多用在算法决策系统中,外部用户只须要决定用哪一个算法便可。

 

 

## 模板方法模式(Template Method)

解释一下模板方法模式,就是指:一个抽象类中,有一个主方法,再定义1...n个方法,能够是抽象的,也能够是实际的方法,定义一个类,继承该抽象类,重写抽象方法,经过调用抽象类,实现对子类的调用

public abstract class AbstractCalculator {          /*主方法,实现对本类其它方法的调用*/     public final int calculate(String exp,String opt){         int array[] = split(exp,opt);         return calculate(array[0],array[1]);     }          /*被子类重写的方法*/     abstract public int calculate(int num1,int num2);          public int[] split(String exp,String opt){         String array[] = exp.split(opt);         int arrayInt[] = new int[2];         arrayInt[0] = Integer.parseInt(array[0]);         arrayInt[1] = Integer.parseInt(array[1]);         return arrayInt;     } }

相关文章
相关标签/搜索