优化又臭又长的if-else,写出优雅的代码

在我们日常开发中,过度使用if...else语句会导致代码可读性下降,维护困难,并且不利于代码的扩展。为了消除这些if...else语句,我们可以利用多种设计模式和技术手段。可探讨下如何优化是的代码变的优雅

1. 使用注解

使用注解可以减少代码中的条件判断,使代码更加清晰。例如,我们可以通过注解来标记需要执行的操作,然后在运行时根据注解的值来决定执行哪个操作。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Operation {
    String value();
}

public class MyService {
    
    @Operation("operation1")
    public void operation1() {
        // 执行操作1
    }

    @Operation("operation2")
    public void operation2() {
        // 执行操作2
    }

    public void executeOperation(String operationName) {
        for (Method method : MyService.class.getDeclaredMethods()) {
            if (method.isAnnotationPresent(Operation.class)) {
                Operation operation = method.getAnnotation(Operation.class);
                if (operation.value().equals(operationName)) {
                    try {
                        method.invoke(this);
                        return;
                    } catch (Exception e) {
                        throw new RuntimeException("Error executing operation", e);
                    }
                }
            }
        }
        throw new IllegalArgumentException("Operation not found: " + operationName);
    }
}

2. 动态拼接名称

动态拼接名称在某些情况下可以减少if...else的使用,但这通常用于构建字符串或动态访问属性,而不是直接替代条件判断。

public class MyComponent {
    private Map<String, Runnable> actions = new HashMap<>();

    public MyComponent() {
        actions.put("action1", this::action1);
        actions.put("action2", this::action2);
    }

    private void action1() {
        // 执行操作1
    }

    private void action2() {
        // 执行操作2
    }

    public void executeAction(String actionName) {
        Runnable action = actions.get(actionName);
        if (action != null) {
            action.run();
        } else {
            throw new IllegalArgumentException("Action not found: " + actionName);
        }
    }
}

3. 模版方法+判断策略+工厂模式

使用模版方法将不变的部分放在父类中,可变的部分通过抽象方法让子类实现。结合判断策略和工厂模式,可以动态选择实现类。

public abstract class Strategy {
    public abstract void execute();
}

public class StrategyA extends Strategy {
    @Override
    public void execute() {
        // 执行策略A
    }
}

public class StrategyB extends Strategy {
    @Override
    public void execute() {
        // 执行策略B
    }
}

public class StrategyFactory {
    public static Strategy getStrategy(String strategyName) {
        switch (strategyName) {
            case "A":
                return new StrategyA();
            case "B":
                return new StrategyB();
            default:
                throw new IllegalArgumentException("Strategy not found: " + strategyName);
        }
    }
}

public class Context {
    private Strategy strategy;

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void executeStrategy() {
        strategy.execute();
    }
}

// 使用时
Context context = new Context();
context.setStrategy(StrategyFactory.getStrategy("A"));
context.executeStrategy();

4. 责任链模式

责任链模式允许将多个条件判断逻辑拆分成单独的处理器,每个处理器负责处理一种或一类特定的请求。请求在处理器链中依次传递,直到被正确处理或遍历完整个链。

首先,定义请求接口和处理器接口:

// 请求接口
public interface Request {
    String getRequestType();
    // 可以包含其他请求相关的方法和属性
}

// 处理器接口
public interface Handler {
    boolean handleRequest(Request request);
    void setNext(Handler nextHandler);
}

然后,实现具体的请求类和处理器类:

// 具体请求类
public class ConcreteRequest implements Request {
    private String requestType;

    public ConcreteRequest(String requestType) {
        this.requestType = requestType;
    }

    @Override
    public String getRequestType() {
        return requestType;
    }
}

// 具体的处理器类A
public class HandlerA implements Handler {
    private Handler nextHandler;

    @Override
    public boolean handleRequest(Request request) {
        if (request.getRequestType().equals("A")) {
            System.out.println("HandlerA 处理请求: " + request.getRequestType());
            return true; // 表示请求已被处理
        }
        return false; // 表示请求未被处理,需要传递给下一个处理器
    }

    @Override
    public void setNext(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }
}

// 具体的处理器类B,与HandlerA类似,处理不同类型的请求
public class HandlerB implements Handler {
    private Handler nextHandler;

    @Override
    public boolean handleRequest(Request request) {
        if (request.getRequestType().equals("B")) {
            System.out.println("HandlerB 处理请求: " + request.getRequestType());
            return true;
        }
        return false;
    }

    @Override
    public void setNext(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }
}

// 可以继续添加更多的处理器类来处理不同类型的请求

最后,在客户端代码中创建处理器链并发送请求:

public class ChainOfResponsibilityPatternDemo {
    public static void main(String[] args) {
        // 创建处理器对象并设置处理器链
        Handler handlerA = new HandlerA();
        Handler handlerB = new HandlerB();
        handlerA.setNext(handlerB);

        // 创建请求对象
        Request request = new ConcreteRequest("A");

        // 发送请求到处理器链
        Handler currentHandler = handlerA;
        while (currentHandler != null) {
            if (currentHandler.handleRequest(request)) {
                break; // 请求已被处理,跳出循环
            }
            currentHandler = currentHandler.getNext(); // 请求未被处理,传递到下一个处理器
        }

        // 发送另一个请求到处理器链,以演示链的传递性
        request = new ConcreteRequest("B");
        currentHandler = handlerA; // 重置当前处理器为链的起始点
        while (currentHandler != null) {
            if (currentHandler.handleRequest(request)) {
                break;
            }
            currentHandler = currentHandler.getNext();
        }
    }
}

在这个示例中,我们创建了两个处理器HandlerAHandlerB,分别处理不同类型的请求。在客户端代码中,我们创建了一个请求对象,并将其发送到处理器链的起始点handlerA。然后,我们遍历处理器链,直到找到能够处理该请求的处理器为止。如果链中没有处理器能够处理请求,则请求会在链的末尾被丢弃。

通过这种方式,我们可以将原来复杂的if-else结构拆分成多个独立的处理器,每个处理器只关注一种或一类特定的请求。这使得代码更加模块化和可维护,同时也提高了扩展性,因为我们可以轻松地添加新的处理器来处理新的请求类型。

  • 13
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值