在之前的文章中,我们探讨了如何使用表数据结构来优化条件判断。今天,我们来分享另一种在Java中简化代码逻辑的优雅方案:利用枚举类(Enum) 来消除繁琐的 if...else 或 switch 语句。
示例需求
模拟一个汽车经销商的场景:根据用户选择的不同汽车品牌,从对应的生产工厂为用户获取一辆指定型号的汽车。
示例环境
- 操作系统:Ubuntu 24.04.2 LTS
- Java 版本:JDK 21.0.2
- 构建工具:Apache Maven 3.9.8
- 开发工具:IntelliJ IDEA 2025.1.3 (Community Edition)
示例代码
1. 定义汽车实体类
首先,创建一个简单的 Car 记录类,用于表示汽车对象。
package com.projdk.example.enums;
public record Car(String brand, String model) {
}
2. 定义工厂接口及其实现
定义一个汽车工厂接口 ICarFactory,以及针对不同品牌的具体工厂实现。
工厂接口:
package com.projdk.example.enums;
public interface ICarFactory {
Car getCar(String model);
}
奥迪汽车工厂实现:
package com.projdk.example.enums;
public class AudiCarFactory implements ICarFactory {
@Override
public Car getCar(String model) {
return new Car("Audi", model);
}
}
别克汽车工厂实现:
package com.projdk.example.enums;
public class BuickCarFactory implements ICarFactory {
@Override
public Car getCar(String model) {
return new Car("Buick", model);
}
}
3. 创建核心枚举类
这是消除条件判断的关键。我们创建一个 CarBrand 枚举,每个枚举实例都持有一个对应的工厂对象。
package com.projdk.example.enums;
public enum CarBrand {
AUDI(new AudiCarFactory()),
BUICK(new BuickCarFactory());
private ICarFactory carFactory;
CarBrand(ICarFactory carFactory) {
this.carFactory = carFactory;
}
public Car getCar(String model) {
return this.carFactory.getCar(model);
}
}
4. 定义用户选项与经销商
创建 Options 记录类来封装用户的选择,以及 CarVender 经销商类来执行购车逻辑。
用户选项类:
package com.projdk.example.enums;
public record Options(CarBrand brand, String model) {
}
汽车经销商类:
注意,这里的 getCar 方法非常简洁,直接通过枚举实例调用方法,没有任何条件判断。
package com.projdk.example.enums;
public class CarVender {
public Car getCar(Options options) {
return options.brand().getCar(options.model());
}
}
5. 编写测试代码
最后,我们编写一个测试类来验证整个流程。
package com.projdk.example.test;
import com.projdk.example.enums.Car;
import com.projdk.example.enums.CarBrand;
import com.projdk.example.enums.CarVender;
import com.projdk.example.enums.Options;
import org.junit.jupiter.api.Test;
public class CarEnumTestCase {
@Test
public void testCar() throws Exception {
CarVender carVender = new CarVender();
Car car = carVender.getCar(new Options(CarBrand.AUDI, "A6L"));
System.out.println(car);
car = carVender.getCar(new Options(CarBrand.BUICK, "LaCrosse"));
System.out.println(car);
}
}
运行测试,结果如下:

总结
通过这个例子,我们可以看到枚举类如何将行为(工厂方法)与数据(品牌类型)紧密绑定。当需要根据某个“类型”执行不同操作时,传统的 if-else 或 switch 语句会随着类型增加而不断膨胀,代码可读性和可维护性下降。
而使用枚举策略模式后:
- 扩展性强:新增一个品牌(如
Benz),只需增加一个枚举实例并关联新的工厂类,核心经销商 CarVender 的代码无需任何改动。
- 职责清晰:每个品牌的创建逻辑封装在各自的工厂和枚举定义中,符合单一职责原则。
- 消除条件判断:业务逻辑中不再出现冗长的条件分支,代码更加简洁优雅。
与之前介绍的“注册表”(Map结构)方法相比,枚举方案在编译时就能确保所有类型都被处理,更具类型安全性,尤其适合类型已知且相对固定的场景。而Map方案则更适合需要动态注册和查找的场景,灵活性更高。
在云栈社区与其他开发者交流时,我们常探讨这类代码优化技巧。那么,在实际编码中,面对一个具体的需求,你会如何在这两种方案甚至更多设计模式中做出选择呢?欢迎分享你的见解。