策略模式
定义了算法,分别封装起来,让他们之间可以相互替换,此模式让算法的变化不会影响到使用算法的用户
/**
*定义一个抽象的父类,包含一个抽象的算法Amethod
*
/
public abstract class Strategy {
public abstract void Amethod();
}
/**
*A类用A的实现去实现算法A
*
/
public class ConcreteStrategyA extends Strategy{
/**
* 算法A的具体实现
*/
@Override
public void Amethod() {
// TODO Auto-generated method stub
}
}
/**
*同样的可以有B或者C,D算法
*
/
配置一个Context来维护Strategy的引用
public class Context {
Strategy strategy;
public Context(Strategy strategy) {
// TODO Auto-generated constructor stub
this.strategy = strategy;
}
/**
* 上下文接口,根据具体的策略对象,调用其算法的方法
*/
public void ContextInterface() {
strategy.Amethod();
}
}
/**
* 根据不同的需求去实例化不同的算法
*/
Context context = new Context(new ConcreteStrategyA());
Context contextB = new Context(new ConcreteStrategyB());
//实例化对象不同,所以调用的算法就不同
策略模式+简单工厂
- 加上简单工厂的话,就是在上下文管理类的地方使用上工厂类,传入不同的值,就实例化不同的对象。
Strategy strategy;
public Context(String type) {
// TODO Auto-generated constructor stub
switch (type) {
case "A":
this.strategy = new ConcreteStrategyA();
break;
case "B":
this.strategy = new ConcreteStrategyB();
default:
break;
}
}
/**
* 上下文接口,根据具体的策略对象,调用其算法的方法
*/
public void ContextInterface() {
strategy.Amethod();
}
/**
* 根据不同的需求去实例化不同的算法
*/
Context contextA = new Context("A");
contextA.ContextInterface();
Context contextB = new Context("B");
contextB.ContextInterface();