策略模式UML:
ContextType1、ContextType2在构造方法或set方法中初始化各自需要的StrategyType
策略模式代码
/**
* 策略接口
*/
public interface Strategy {
public void strategyInterfaceMethod();
}
/**
* 具体策略A
*/
public class StrategyTypeA implements Strategy {
@Override
public void strategyInterfaceMethod() {
// todo someting
}
}
/**
* 具体策略B
*/
public class StrategyTypeB implements Strategy {
@Override
public void strategyInterfaceMethod() {
// todo someting
}
}
/**
* 上下文抽象类
* 我理解的这个类的作用是:负责策略与用户(使用者)的连接,也是策略模式的入口
*/
public AbstractClass Context {
//持有一个具体策略的对象
private Strategy strategy;
/**
* 构造函数,传入一个具体策略对象
* @param strategy
*/
public Context(Strategy strategy){
this.strategy = strategy;
}
/**
* 策略方法
*/
public void contextMethod(){
strategy.strategyInterfaceMethod();
}
}
/**
* 具体环境类
*/
public Class ContextType1 extends Context{
public void contextMethod(){
strategy.strategyInterfaceMethod();
// todo something
}
}
应用场景: 多个用户购买不同型号电脑
public class Client {
public static void main(String[] args) {
// 客户需要定制自己需要的策略
// 策略1--购买戴尔电脑
Strategy dell = new StrategyTypeA();
dell.setCPU("AMD");
dell.setScreen("LGD");
// 策略2
Strategy macbook = new StrategyTypeB();
macbook.setCPU("Intel");
macbook.setScreen("sansung");
// 购买的是dell电脑
// 用户将自己需要的策略(电脑配置)交给商家
ContextType1 customer1 = new ContextType1(dell);
// buyComputer方法中的strategy.strategyInterfaceMethod(); = StrategyTypeA.strategyInterfaceMethod();
customer1.buyComputer();
// 购买的是macbook
ContextType2 customer2 = new ContextType2(macbook);
// buyComputer方法中的strategy.strategyInterfaceMethod(); = StrategyTypeB.strategyInterfaceMethod();
customer2.buyComputer();
}
}