策略模式

/*
 * TreeSet TreeMap中比较器的传入就是典型的策略模式
 */
public class StrategyTest //策略模式测试类
{
	public static void main(String[] args)
	{
		Environment st = new Environment(new AddStrategy());
		System.out.println(st.calculate(10,30));
		Environment st1 = new Environment(new SubStrategy());
		System.out.println(st1.calculate(10,30));
		Environment st2 = new Environment(new MulStrategy());
		System.out.println(st2.calculate(10,30));
		Environment st3 = new Environment(new DivStrategy());
		System.out.println(st3.calculate(10,30));
		
	}
}
 interface Strategy //抽象策略角色
{
  public int cal(int a,int b);
}
class Environment //环境角色
{
	private Strategy strategy;
  public Environment(Strategy strategy)
  {
	  this.strategy = strategy;
  }
	public Strategy getStrategy()
	{
		return strategy;
	}

	public void setStrategy(Strategy strategy)
	{
		this.strategy = strategy;
	}
    public int calculate(int a,int b)
    {
    	return strategy.cal(a,b);   
    }
}
class AddStrategy implements Strategy //具体策略角色
{

	@Override
	public int cal(int a, int b)
	{
		return a+b;
	}
}

class SubStrategy implements Strategy
{

	@Override
	public int cal(int a, int b)
	{
		return a-b;
	}
}
class MulStrategy implements Strategy
{

	@Override
	public int cal(int a, int b)
	{
		return a*b;
	}
}
class DivStrategy implements Strategy
{

	@Override
	public int cal(int a, int b)
	{
		return a/b;
	}
}


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