为了防止大量的if...else...
或switch case
代码的出现,可以使用策略模式+工厂模式进行优化。
在我的项目当中,报表繁多,所以尝试了这种方式进行优化报表的架构。
代码很简单,如下:
Factory工厂类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Service public class ReportFactory {
@Autowired private final Map<String, ReportService> reportIns = new ConcurrentHashMap<>();
public ReportService getReportIns(String code) { ReportService reportInstance = reportIns.get(code); if (reportInstance == null) { throw new RuntimeException("未定义reportInstance"); }
return reportInstance; }
}
|
接口
1 2 3
| public interface ReportService { String getResult(); }
|
实现类
1 2 3 4 5 6 7 8
| @Component(value = "A1") public class ReportServiceA1 implements ReportService {
@Override public String getResult() { return "我是A1"; } }
|
1 2 3 4 5 6 7 8
| @Component(value = "A2") public class ReportServiceA2 implements ReportService {
@Override public String getResult() { return "我是A2"; } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @SpringBootTest public class BlogServerApplicationTest {
@Autowired ReportFactory reportFactory;
@Test public void test2() { String result1 = reportFactory.getReportIns("A1").getResult(); System.out.println("-----------------"); System.out.println(result1); String result2 = reportFactory.getReportIns("A2").getResult(); System.out.println("-----------------"); System.out.println(result2); } }
|
打印如下:
1 2 3 4
| ----------------- 我是A1 ----------------- 我是A2
|
总结
在平时的工作当中,写一些业务代码是无可避免的,但是只要不局限于现状,往往可以发现不一样的乐趣。就像我在报表的业务中学习到了策略模式+工厂模式。
个人博客网址: https://colablog.cn/
如果我的文章帮助到您,可以关注我的微信公众号,第一时间分享文章给您
