策略模式

 

 

一.组成部分:

1. 环境角色:持有一个策略类引用 

2. 抽象策略(策略类的抽象方法) 

3. 具体策略:相关的算法或操作(抽象方法的实现类)

 

代码:

 

/**
 * 策略模式的 执行 环境 
* @ClassName: Enviroment
* @Description: 
* @author wangzhantao
* @date 2013-3-11 下午04:32:36
*
 */
public class Enviroment {
	private Strategy strategy;
	public Enviroment(Strategy strategy){
		this.strategy = strategy;
	}
	public Integer calculate(int a, int b){
		return strategy.calculate(a, b) ;
	}
	public Strategy getStrategy() {
		return strategy;
	}
	public void setStrategy(Strategy strategy) {
		this.strategy = strategy;
	}
}

 

2 策略类的方法或接口

public interface Strategy {

	public int calculate(int a,int b);
}

 3 抽象策略的实现类

 

 

//减 策略 
public class SubtractdStrategy implements Strategy{
	@Override
	public int calculate(int a, int b) {
		return  a-b;
	}

}

 

  

//乘法策略
public class MultiplyStrategy implements Strategy{
	@Override
	public int calculate(int a, int b) {
		return  a*b;
	}
}

 

 4  策略模式的测试类

   

//策略模式的测试类
public class TestStrategy {
	public static void main(String[] args) {
		Strategy  strategy = new DivideStrategy();
		Enviroment  enviroment= new Enviroment(strategy);
		System.out.println(  enviroment.calculate(10, 2) );
	}
}

 

你可能感兴趣的:(策略模式)