设计模式应用(多个if的处理)

使用场景

如果在代码中出现大量if判断,再执行一些比较复杂的业务操作,类似于以下情况。

    @Test
    void test() {
        String str = "A";
        if (str.equals("A")) {
            System.out.println("A的方法1");
        } else if (str.equals("B")) {
            System.out.println("B的方法1");
        }
    }

此时如果使用if的重复判断,则代码过于冗长。

解决方法

采用工厂模式,策略模式,模版方法设计模式
1、创建一个抽象类,实现InitializingBean接口,由if对应条件的子类来实现

/**
 * 模版方法设计模式
 */
public abstract class FunService implements InitializingBean {
    public void fun1() {
        throw new UnsupportedOperationException();
    }

    public void fun2() {
        throw new UnsupportedOperationException();
    }
}

2、子类实现


import com.example.demo.manage.FunFactory;
import com.example.demo.service.FunService;
import org.springframework.stereotype.Service;

@Service
public class AService extends FunService {

    @Override
    public void fun1() {
        System.out.println("A的方法1");
    }

    @Override
    public void fun2() {
        System.out.println("A的方法2");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        FunFactory.register("A", this);

    }
}

InitializingBean接口
方法afterPropertiesSet 是在类中的属性被注入后,再执行,一般用于对不可注入的类变量进行定义。

3、定义工厂,和策略的map

/**
 * 工厂模式 策略模式
 */
public class FunFactory {
    private static Map<String, FunService> map = new HashMap<>();


    public static FunService getService(String str) {
        return map.get(str);
    }

    public static void register(String str, FunService service) {
        if (StringUtils.isEmpty(str) || Objects.isNull(service)) return;
        map.put(str, service);
    }
}

在所有实现类的afterPropertiesSet方法中,向工厂注册。
4、执行

    @Test
    void contextLoads() {
        String str = "A";
        FunService service = FunFactory.getService(str);
        service.fun1();
    }

小节

改进后的代码符合开闭原则,即是对于新的条件,只需要添加一个javabean,而不需言重新修改代码。

git 地址

https://github.com/lexiaoyao1995/design_mode

posted @ 2020-08-19 16:05  刃牙  阅读(3055)  评论(0编辑  收藏  举报