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.
package javaPattern;

public interface Strategy {
	public void execute();
}
class ConcreteStrategyA implements Strategy{
	public void execute(){
		System.out.println("算法A");
	}
}
class ConcreteStrategyB implements Strategy{
	public void execute(){
		System.out.println("算法B");
	}
}
class Context{
	
	private Strategy strategy;
	public Context(Strategy strategy){
		this.strategy = strategy;
	}
	public void someMethod(){
		strategy.execute();
	}
	public static void main(String[] args) {
		ConcreteStrategyA csA = new ConcreteStrategyA();
		Context context = new Context(csA);
		context.someMethod();
	}
}

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

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