策略模式
>定义一系列的算法,把它们一个个封装起来, 使它们可相互替换。本模式使得算法可独
>立于使用它的客户而变化。
IStrategy
抽象策略
public interface IStrategy {
void execute();
}
StrategyOne
具体策略
public class StrategyOne implements IStrategy {
@Override
public void execute() {
System.out.println("I am StrategyOne");
}
}
StrategyTwo
具体策略
public class StrategyTwo implements IStrategy {
@Override
public void execute() {
System.out.println("I am StrategyTwo");
}
}
StrategyExecutor
策略执行器
public class StrategyExecutor {
private IStrategy strategy;
public IStrategy getStrategy() {
return strategy;
}
public void setStrategy(IStrategy strategy) {
this.strategy = strategy;
}
public void execute() {
strategy.execute();
}
}
网友评论