用加减来简单的看策略类
策略类的组成:
1.抽象策略角色:通常由一个接口或者策略类组成;
2.具体的策略角色:里面封装着相关的算法和行为;
3.环境角色:持有一个策略类的引用,为客户端所调用;
作用:
(自己的理解):将客户端与相关的算法分开,使其互相不干涉。
实现:
1.要有一个抽象策略角色: Strategy(Interface);
2.要有相关具体的策略角色,来封装这些算法和行为:class
AddStratety、class
SubstarctStrategy
3.要有环境角色:Environment;
编写:
抽象策略角色---Strategy:
public interface Strategy
{
public int Calculate(int a, int b);
}
具体策略角色--AddStrategy
public class Addstrategy implements Strategy
{
@Override
public int Calculate(int a, int b)
{
return a + b;
}
}
具体策略角色--SubstractStrategy
public class SubstractStrategy implements Strategy
{
@Override
public int Calculate(int a, int b)
{
return a - b;
}
}
3.环境角色--Environment;
public 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.Calculate(a, b);
}
}
客户端--Client
public class Client
{
public static void main(String[] args)
{
Addstrategy addstrategy = new Addstrategy();
Environment environment = new Environment(addstrategy);
System.out.println(environment.Calculate(3, 4));
SubstractStrategy substractstrategy = new SubstractStrategy();
environment.setStrategy(substractstrategy);
System.out.println(environment.Calculate(3, 4));
}
}
由客户端中的程序可以看出:当写进一个策略方法的时候,程序为根据策略方法的算法来计算传进的值。避免使用繁琐的if
else循环。