一、策略模式是什么?
定义了算法策略,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法策略的用户。
二、策略模式优缺点
- 可以替换到耦合性高的IF-ELSE;
- 代码优雅、可复用扩展、便于维护;
- 策略如果很多的话,会造成策略类膨胀;
- 使用者必须清楚所有的策略类及其用途;
三、策略模式示例
1.定义策略接口
/**
* 抽象策略类 --吃饭
* @Author:lzf
* @Date: 2023-3-15
*/
public interface DineStrategy {
void eat();
}
2.定义具体策略类,继承策略接口
/**
* 具体的策略实现 -- 吃汉堡
* @Author:lzf
* @Date: 2023-3-15
*/
@Service("hamburg")
public class HamburgConcreteStrategy implements DineStrategy{
@Override
public void eat() {
System.out.println("我在吃汉堡--");
}
}
/**
* 具体的策略实现 -- 吃米饭
* @Author:lzf
* @Date: 2023-3-15
*/
@Service("rice")
public class RiceConcreteStrategy implements DineStrategy{
@Override
public void eat() {
System.out.println("米饭真好吃!嘎嘎--");
}
}
3.调用策略
标准的策略模式还有个Context
类用于操作策略的上下文环境,这里示例直接使用的是spring
框架,根据对应名称找到对应的实现类。
@SpringBootTest
public class StrategyTest {
@Resource
ApplicationContext applicationContext;
@Test
void test(){
// 实际开发中可以用 参数来调用
DineStrategy rice = applicationContext.getBean("rice", DineStrategy.class);
rice.eat();
DineStrategy hamburg = applicationContext.getBean("hamburg", DineStrategy.class);
hamburg.eat();
}
}