策略模式
1、对象行为型模式,在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改;
2、java中使用 通过实现相同的接口,实现接口中相同的方法,通过其中的一个方法决定实际使用的是什么策略,通过另一个或多个方法去定义实现方法的方式;
例如:
public interface StrategyServiceTest {
boolean isdo(int type);
void doIt();
}
@Service
public class RunStrategyServiceImpl implements StrategyServiceTest {
@Override
public boolean isdo(int type) {
return 1 == type;
}
@Override
public void doIt() {
System.out.println(1);
}
}
@Service
public class RunStrategy_2ServiceImpl implements StrategyServiceTest {
@Override
public boolean isdo(int type) {
return 2 == type;
}
@Override
public void doIt() {
System.out.println(2);
}
}
@Service
public class RunStrategy_3ServiceImpl implements StrategyServiceTest {
@Override
public boolean isdo(int type) {
return 3 == type;
}
@Override
public void doIt() {
System.out.println(3);
}
}
public static void main(String[] args) {
// 这里可以使用注入bean的方式,使用接口类 不需要具体new 出来;
StrategyServiceTest bean = new RunStrategy_3ServiceImpl();
if(bean.isdo(1))
bean.doIt();
if(bean.isdo(2))
bean.doIt();
if(bean.isdo(3))
bean.doIt();
// 结果 3
}