デザインモード----ポリシーモード


戦略モードは一連のアルゴリズムを定義し,各アルゴリズムをカプセル化し,また相互に置換できるようにした.戦略パターンは、アルゴリズムを顧客と独立して使用して変化させる.(原文:The Strategy Pattern defines a family of algorithms、encapsultes each one、and makes them interchange ble.Strategy lets the algorithm vary independently from clients that it)
 
実例
アルゴリズムインターフェース:Strategy.java
package strategy;

public interface Strategy {
	public void AlgorithmInterface();
}
 
具体的なアルゴリズムA実装:Cocrete StrategyA.java
package strategy;

public class ConcreteStrategyA implements Strategy {

	@Override
	public void AlgorithmInterface() {
		// TODO Auto-generated method stub
		System.out.println("    A  ");
	}

}
 
具体的なアルゴリズムB実装:Cocrete StrategyB.java
package strategy;

public class ConcreteStrategyB implements Strategy {

	@Override
	public void AlgorithmInterface() {
		// TODO Auto-generated method stub
		System.out.println("    B  ");
	}

}
 
コンテキストクラスでは、Strategyオブジェクトの参照を維持します.Contect.java
package strategy;

public class Context {
	
	public Context(Strategy strategy) {	//    ,         
		this.strategy = strategy;
	}
	
	public void contextInterface() {
		strategy.AlgorithmInterface();
	}
	
	private Strategy strategy;
}
 
Main関数:Main.java
package strategy;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Context context;
		
		//  A
		context = new Context(new ConcreteStrategyA());
		context.contextInterface();
		//  B
		context = new Context(new ConcreteStrategyB());
		context.contextInterface();
	}

}