design pattern——策略模式

针对问题:在许多继承体系结构中,经常出现的一些问题是在超类中的一些接口只需在部分子类中存在。或者是超类中的接口在子类中的实现算法大同小异,就那么几种方式,这样的话每当添加一个子类就不得不在已存在某个子类中复制粘贴,没有达到复用的目的。

策略模式的结构:

策略模式的java实现:

/**
 * 抽象类(将那些用继承不能解决的接口换成 用组合接口的形式实现动态改变形为)
 * @author bruce
 *
 */
public abstract class Context {
	
	/**
	 * 组合策略接口
	 */
	protected Strategy strategy;
	
	/**
	 * 委托策略形为
	 */
	public void performAlgorithm(){
		strategy.algorithmInterface();
	}
	
	public abstract void otherInterface();

	
	
	public Strategy getStrategy() {
		return strategy;
	}

	public void setStrategy(Strategy strategy) {
		this.strategy = strategy;
	}
	
	
}



/**
 * 策略接口
 * @author bruce
 *
 */
public interface Strategy {
	
	public void algorithmInterface();
}



/**
 * 策略实现(算法A)
 * @author bruce
 *
 */
public class ConcreteStrategyA implements Strategy{

	public void algorithmInterface() {
		// TODO Auto-generated method stub
		System.out.println("A 算法");
	}

}


/**
 * 策略实现(算法B)
 * @author bruce
 *
 */
public class ConcreteStrategyB implements Strategy{

	public void algorithmInterface() {
		// TODO Auto-generated method stub
		System.out.println("B 算法");
	}

}






/**
 * 实现类(实现重构后的抽象类)
 * @author bruce
 *
 */
public class ConcreteContext extends Context{
	
	public ConcreteContext(){
		strategy=new ConcreteStrategyA();
	}

	@Override
	public void otherInterface() {
		// TODO Auto-generated method stub
		
	}
}



/**
 * 测试
 * @author bruce
 *
 */
public class Client {
	public static void main(String[] args) {
		Context context=new ConcreteContext();//ConcreteContext默认为A算法
		context.performAlgorithm(); //output:A 算法
		
		Strategy strategyB=new ConcreteStrategyB();
		context.setStrategy(strategyB);//改变context的算法
		context.performAlgorithm();//output:B 算法
	}
} 

猜你喜欢

转载自xieyaxiong.iteye.com/blog/1584125