Article directory
1. What is the strategic model?
Algorithm strategies are defined and encapsulated separately so that they can be replaced with each other. This mode allows changes in the algorithm to not affect users who use the algorithm strategy.
2. Advantages and Disadvantages of Strategy Model
- Can be replaced by IF-ELSE with high coupling;
- The code is elegant, reusable and extendable, and easy to maintain;
- If there are too many strategies, it will cause the strategy class to expand;
- Users must be aware of all policy classes and their uses;
3. Example of Strategy Pattern
1. Define the policy interface
/**
* 抽象策略类 --吃饭
* @Author:lzf
* @Date: 2023-3-15
*/
public interface DineStrategy {
void eat();
}
2. Define specific strategy classes and inherit the strategy interface
/**
* 具体的策略实现 -- 吃汉堡
* @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. Call strategy
The standard strategy pattern also has a Context
class for operating the context of the strategy. The example here uses spring
the framework directly and finds the corresponding implementation class according to the corresponding name.
@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();
}
}