Java设计模式之策略模式

STRATEGY  (Object Behavioral) 
Purpose 
Defines a set of encapsulated algorithms that can be swapped 
to carry out a specific behavior. 
Use When 
    1 The only difference between many related classes is their 
       behavior. 
    2 Multiple versions or variations of an algorithm are required. 
    3 Algorithms access or utilize data that calling code shouldn’t 
       be exposed to. 
    4 The behavior of a class should be defined at runtime. 
    5 Conditional statements are complex and hard to maintain. 
Example 
When importing data into a new system different validation 
algorithms may be run based on the data set. By configuring the 
import to utilize strategies the conditional logic to determine 
what validation set to run can be removed and the import can be 
decoupled from the actual validation code. This will allow us to 
dynamically call one or more strategies during the import. 

Java代码 
  1. package javaPattern;  
  2.   
  3. public interface Strategy {  
  4.     public void execute();  
  5. }  
  6. class ConcreteStrategyA implements Strategy{  
  7.     public void execute(){  
  8.         System.out.println("算法A");  
  9.     }  
  10. }  
  11. class ConcreteStrategyB implements Strategy{  
  12.     public void execute(){  
  13.         System.out.println("算法B");  
  14.     }  
  15. }  
  16. class Context{  
  17.       
  18.     private Strategy strategy;  
  19.     public Context(Strategy strategy){  
  20.         this.strategy = strategy;  
  21.     }  
  22.     public void someMethod(){  
  23.         strategy.execute();  
  24.     }  
  25.     public static void main(String[] args) {  
  26.         ConcreteStrategyA csA = new ConcreteStrategyA();  
  27.         Context context = new Context(csA);  
  28.         context.someMethod();  
  29.     }  
  30. }  

Strategy模式与Template Method模式都是对不同算法的抽象与封装,但它们的实现粒度不一样。Strategy模式从类的角度,对整个算法加以封装,Template Method模式从方法的角度,对算法的一部分加以封装,且Template Method模式有一个方法模板的概念,在作为抽象类的父类里,定义了一个具有固定算法并可以细分为多个步骤的模板方法(public)。

你可能感兴趣的:(java,设计模式,算法,Access)