用工厂模式和策略模式优化过多的if-else

时间:2023-03-09 09:04:36
用工厂模式和策略模式优化过多的if-else

多个if-else代码:

@RunWith(SpringRunner.class)
@SpringBootTest
public class EducationalBackgroundTest {
private int year = 6; @Test
public void normalIfElse(){
if ( year == 6){
System.out.println("小学毕业");
}else if ( year == 9){
System.out.println("初中毕业");
}else if ( year == 12){
System.out.println("高中毕业");
}else {
System.out.println("未知学习时间");
}
}
}

上面只统计了3个学习时间,如果我们要写其他的学习时间就需要继续添加if-else,如果业务很复杂,那么这个代码看起来会很乱,不方便维护;

下面用策略模式和工厂模式优化该if-else;

1. 定义抽象策略角色(接口)

public interface EducationalBackground {
void process();
}

2. 编写具体策略角色(实现策略角色接口)

小学毕业策略角色:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component; @Component
public class Primary implements EducationalBackground,InitializingBean { @Override
public void process() {
System.out.println("小学毕业");
}
@Override
public void afterPropertiesSet() throws Exception {
EducationBackgroundFactory.put(6,this);
} }

这里的InitializingBean接口(具体看Spring Bean的生命周期)只有一个方法afterPropertiesSet,实现了该接口的bean初始化会调用这个方法;

再写一个策略角色“初中毕业”:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component; @Component
public class Junior implements EducationalBackground,InitializingBean { @Override
public void process() {
System.out.println("初中毕业");
}
@Override
public void afterPropertiesSet() throws Exception {
EducationBackgroundFactory.put(9,this);
} }

3. 环境角色,内部持有一个策略类的引用

简单工厂模式

import java.util.HashMap;
import java.util.Map;
import java.util.Optional; public class EducationBackgroundFactory {
private static Map<Integer,EducationalBackground> educationMap = new HashMap<>(); private EducationBackgroundFactory(){} private final static EducationalBackground EMPTY = new EmptyDesc(); /**
* 将对应年数的学历对象注册到Map中
* @param year
* @param educationalBackground
*/
public static void put(int year,EducationalBackground educationalBackground){
educationMap.put(year,educationalBackground);
} /**
*获得对应学历对象
* @param year
*/
public static EducationalBackground get(int year){
EducationalBackground educationalBackground = educationMap.get(year);
//没有对应year返回EMPTY
return Optional.ofNullable(educationalBackground).orElse(EMPTY);
} private static class EmptyDesc implements EducationalBackground{
@Override
public void process() {
System.out.println("未知的学习时间year");
}
} }

测试方法:

@RunWith(SpringRunner.class)
@SpringBootTest
public class EducationalBackgroundTest {
private int year = 6; /**
* 设计之后仅需两行代码
*/
@Test
public void design(){
EducationalBackground educationalBackground = EducationBackgroundFactory.get(year);
educationalBackground.process();
} }

用工厂模式和策略模式优化过多的if-else

有关于year的参数最好是配置在配置文件中,比如项目已上线,只需要修改配置文件中的内容即可修改对应的引用,而不需要修改代码(修改了代码需要发布)!

参考来源:

https://www.cnblogs.com/pfblog/p/7815238.html