设计模式--策略模式(Java实现)
时间:2019-06-12
本文章向大家介绍设计模式--策略模式(Java实现),主要包括设计模式--策略模式(Java实现)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
策略模式
在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
在策略模式中,我们创建表示各种策略的对象和一个随着行为变化而选择不同策略对象的 context 对象。策略对象改变 context 对象的执行算法。
实现流程:
1.创建接口,统一策略行为
2.所有策略实现接口行为,写自己对应的业务逻辑,所有的策略都向Spring容器注册
3.创建上下文类(context),并将所有的策略对象放入Map容器
4.根据不同的行为调用上下文对象获取不同的策略对象,执行相应逻辑
Demo:
package com.swt.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.math.BigDecimal; @RestController @SpringBootApplication public class DemoApplication { @Autowired private StrategyContext strategyContext; @RequestMapping ( "calculatePrice" ) public BigDecimal calculatePrice(String memberLevel) { return strategyContext.calculatePrice(memberLevel); } public static void main(String[] args) { SpringApplication.run(DemoApplication. class , args); } } |