策略模式浅析
写点笔记
共 3308字,需浏览 7分钟
·
2021-05-23 21:55
public interface BaseStrategy {
int totalPrice = 0;
/**
* 测试策略模式
*/
void test();
}
public class StrategyA implements BaseStrategy {
/**
* 测试A
*/
public void test() {
System.out.println("策略A");
}
}
public class StrategyB implements BaseStrategy{
/**
* 测试B
*/
public void test() {
System.out.println("策略B");
}
}
public class StrategyC implements BaseStrategy{
/**
* 测试C
*/
public void test() {
System.out.println("策略C");
}
}
/**
* 总领全局
*/
public class StrategyContent {
/**
* 引子
*/
private BaseStrategy baseStrategy;
/**
* 巧用构造函数,关联具体策略
*/
public StrategyContent(int type){
switch (type){
case 1:
baseStrategy=new StrategyA();
break;
case 2:
baseStrategy=new StrategyB();
break;
case 3:
baseStrategy=new StrategyC();
break;
default:
break;
}
}
/**
* 总领调度
*/
public void testStrategy(){
baseStrategy.test();
}
}
public class OriginStrategy {
/**
* 基础策略模式
*/
BaseStrategy baseStrategy;
/**
* 初始化
* @param baseStrategy
*/
OriginStrategy(BaseStrategy baseStrategy){
this.baseStrategy=baseStrategy;
}
/**
* 策略调用
*/
public void test(){
this.baseStrategy.test();
}
}
public class TestStrategyContentMain {
/**
* 业务调用方
* @param args
*/
public static void main(String[] args) {
OriginStrategy originStrategy;
switch (1){
case 1:
originStrategy=new OriginStrategy(new StrategyA());
break;
case 2:
originStrategy=new OriginStrategy(new StrategyB());
break;
case 3:
originStrategy=new OriginStrategy(new StrategyC());
break;
default:
throw new IllegalStateException("Unexpected value: " + 1);
}
originStrategy.test();
}
}
评论