深入解析|完整示例|高频问答|最佳实践
java简单工厂模式的实现属于创建型设计模式的一种变体,虽未被 GoF(四人组)正式归入 23 种经典模式,但在实际开发中被广泛使用。其核心思想是:**由一个专门的工厂类负责封装对象的创建逻辑,客户端仅需传入参数,即可获得所需对象实例,无需直接调用构造函数**。
该模式适用于以下典型场景:
需特别注意:当产品类型频繁扩展时,简单工厂类会因不断修改 switch-case 或 if-else 分支而违背开闭原则(对扩展开放,对修改封闭),此时应考虑转向工厂方法模式或抽象工厂模式。
⚡ 关键辨析:简单工厂 ≠ 工厂方法模式。前者是“一个工厂类统一创建”,后者是“多个具体工厂类各司其职”,后者更符合面向接口编程原则。
从代码维护性角度看,java简单工厂模式的实现本质是将“创建职责”集中化,牺牲了部分灵活性以换取实现简洁性,适合中小型项目或产品形态稳定的模块。
java简单工厂模式的实现包含三类核心角色:
Operation 接口;AddOperation、SubOperation;createOperation(String type) 根据参数实例化不同产品。其 UML 类图结构如下:
| 角色 | 职责 | 典型实现 |
|---|---|---|
| Product | 抽象产品接口 | public interface Operation { double calculate(double a, double b); } |
| ConcreteProduct A | 具体产品A | public class AddOperation implements Operation { public double calculate(double a, double b) { return a + b; } } |
| ConcreteProduct B | 具体产品B | public class SubOperation implements Operation { public double calculate(double a, double b) { return a - b; } } |
| Factory | 静态工厂 | public class OperationFactory { public static Operation createOperation(String type) { ... } } |
此结构清晰体现“高内聚、低耦合”原则:客户端仅依赖 Operation 接口,新增产品时仅需新增实现类并修改工厂分支逻辑(虽违反开闭原则,但可通过反射等技术缓解)。
以下为一个完整的计算器示例,覆盖加减乘除四则运算,支持用户输入参数动态创建运算对象:
public interface Operation {
double calculate(double a, double b);
}
public class AddOperation implements Operation {
@Override
public double calculate(double a, double b) {
return a + b;
}
}
public class SubOperation implements Operation {
@Override
public double calculate(double a, double b) {
return a - b;
}
}
public class MulOperation implements Operation {
@Override
public double calculate(double a, double b) {
return a * b;
}
}
public class DivOperation implements Operation {
@Override
public double calculate(double a, double b) {
if (b == 0) {
throw new IllegalArgumentException("除数不能为零");
}
return a / b;
}
}
public class OperationFactory {
public static Operation createOperation(String type) {
switch (type.toLowerCase()) {
case "add":
case "+":
return new AddOperation();
case "sub":
case "-":
return new SubOperation();
case "mul":
case "*":
return new MulOperation();
case "div":
case "/":
return new DivOperation();
default:
throw new IllegalArgumentException("不支持的操作类型: " + type);
}
}
}
public class ClientDemo {
public static void main(String[] args) {
Operation addOp = OperationFactory.createOperation("add");
System.out.println("5 + 3 = " + addOp.calculate(5, 3)); // 输出:8.0
Operation divOp = OperationFactory.createOperation("/");
System.out.println("10 / 2 = " + divOp.calculate(10, 2)); // 输出:5.0
try {
OperationFactory.createOperation("mod").calculate(10, 3); // 抛出异常
} catch (IllegalArgumentException e) {
System.err.println("错误: " + e.getMessage());
}
}
}
⚙️ 提示:在实际项目中,建议为工厂类添加日志记录与异常处理机制,并通过配置文件(如 factory.properties)管理类型映射,降低硬编码风险。
java简单工厂模式的实现在以下场景中具有显著优势:
当系统需兼容旧版协议(如 HTTP/1.0 与 HTTP/2.0)时,可设计 HttpMessageConverter 接口,由工厂根据请求头动态返回对应解析器:
public interface HttpMessageConverter {
Object decode(String content, Class> targetType);
}
public class JsonConverter implements HttpMessageConverter { ... }
public class XmlConverter implements HttpMessageConverter { ... }
public class MessageConverterFactory {
public static HttpMessageConverter createConverter(String contentType) {
if (contentType.contains("json")) return new JsonConverter();
if (contentType.contains("xml")) return new XmlConverter();
throw new IllegalArgumentException("不支持的内容类型");
}
}
在 JDBC 连接池封装中,可通过工厂根据配置文件中的 db.type(如 mysql、postgresql)动态加载对应驱动类,避免客户端硬编码驱动名:
public class DataSourceFactory {
public static DataSource createDataSource(String dbType) {
switch (dbType) {
case "mysql": return new MysqlDataSource();
case "postgresql": return new PostgreSQLDataSource();
default: throw new UnsupportedOperationException("不支持的数据库类型");
}
}
}
在高并发系统中,根据业务场景选择 Redis、Ehcache 或 Guava Cache,工厂类可统一管理缓存实例创建逻辑:
public interface CacheService {
void put(String key, Object value);
Object get(String key);
}
public class RedisCacheService implements CacheService { ... }
public class EhcacheService implements CacheService { ... }
public class CacheFactory {
private static final String CACHE_TYPE = System.getProperty("cache.type", "redis");
public static CacheService createCache() {
if ("redis".equalsIgnoreCase(CACHE_TYPE)) {
return new RedisCacheService();
} else if ("ehcache".equalsIgnoreCase(CACHE_TYPE)) {
return new EhcacheService();
}
throw new IllegalStateException("未配置缓存类型");
}
}
通过此类设计,业务层仅需调用 CacheFactory.createCache() 即可获得适配当前环境的缓存服务,实现解耦与可配置性。
new 语句;综合评估:在产品类型稳定、创建逻辑简单的场景下,java简单工厂模式的实现是性价比极高的选择;但当系统复杂度提升,应及时升级为工厂方法模式(每个产品对应一个工厂子类)。
当工厂类中 if-else 分支超过 5 个时,建议重构为以下方案之一:
Map<String, Supplier<Operation>> 存储创建函数;❌ 错误示例:将工厂类设计为单例并返回静态对象
// 错误!每次返回同一实例,导致状态污染
public class OperationFactory {
private static final Operation add = new AddOperation();
public static Operation createOperation(String type) {
return "add".equals(type) ? add : new SubOperation();
}
}
✅ 正确做法:每次调用返回新实例(除非对象是无状态的单例,如 Math 类中的常量)
工厂方法应明确抛出 IllegalArgumentException 或自定义异常,而非静默失败或返回 null,否则会导致客户端 NPE 风险:
// 推荐:明确异常语义
public static Operation createOperation(String type) {
switch (type) {
case "add": return new AddOperation();
default: throw new IllegalArgumentException("无效类型: " + type);
}
}
| 维度 | 简单工厂模式 | 工厂方法模式 |
|---|---|---|
| 结构 | 单个工厂类 + 静态方法 | 抽象工厂接口 + 多个具体工厂类 |
| 扩展性 | 新增产品需修改工厂源码 | 新增产品只需新增工厂子类 |
| 符合开闭原则 | ❌ 违背 | ✅ 符合 |
| 代码量 | 较少,适合小型项目 | 较多,适合大型系统 |
| 适用场景 | 产品类型稳定、创建逻辑简单 | 产品族复杂、需多态扩展 |
以计算器为例:
OperationFactory 处理所有运算类型;OperationFactory 接口,由 AddFactory、SubFactory 等各自负责创建。⚡ 经验建议:若未来可能引入“开方”、“取模”等新运算,且需独立管理其生命周期(如缓存、监控),应优先选择工厂方法模式。
直接调用 new AddOperation() 存在以下问题:
AddOperation 替换为 PreciseAddOperation,需修改所有调用点。而工厂模式通过统一入口,使系统具备“开闭支持能力”——新增产品只需扩展工厂,无需改动客户端代码。
对比分析:
| 特性 | 静态工厂方法 | 构造器 |
|---|---|---|
| 命名能力 | ✅ 可自定义有意义的方法名(如 createOperation) | ❌ 仅能用类名 |
| 返回子类实例 | ✅ 可返回接口的任意实现 | ❌ 仅能返回当前类实例 |
| 控制实例数量 | ✅ 可实现单例/对象池 | ❌ 每次调用必新建对象 |
| 泛型推断支持 | ✅ 可简化泛型实例化(如 List.of()) | ❌ 需显式声明泛型 |
典型应用:Java 标准库中 Boolean.valueOf() 比 new Boolean() 更高效,因前者复用 TRUE/FALSE 常量。
推荐三种优化方案:
public class OperationFactory {
private static final Map<String, Supplier<Operation>> OPERATIONS = Map.of(
"add", AddOperation::new,
"sub", SubOperation::new,
"mul", MulOperation::new,
"div", DivOperation::new
);
public static Operation createOperation(String type) {
Supplier<Operation> supplier = OPERATIONS.get(type.toLowerCase());
if (supplier == null) throw new IllegalArgumentException("不支持类型: " + type);
return supplier.get();
}
}
public class OperationFactory {
private static final Map<String, String> TYPE_TO_CLASS = new HashMap<>();
static {
// 从 factory.properties 加载映射
try (InputStream in = OperationFactory.class.getResourceAsStream("/factory.properties")) {
Properties props = new Properties();
props.load(in);
props.forEach((k, v) -> TYPE_TO_CLASS.put(k.toString(), v.toString()));
} catch (IOException e) {
throw new RuntimeException("加载工厂配置失败", e);
}
}
public static Operation createOperation(String type) {
String className = TYPE_TO_CLASS.get(type);
if (className == null) throw new IllegalArgumentException("未配置类型: " + type);
try {
return (Operation) Class.forName(className).getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("实例化失败: " + className, e);
}
}
}
关键差异如下:
简单工厂可视为抽象工厂的特例——当产品族仅含一个产品时,抽象工厂退化为简单工厂。
在 Spring 环境中,可将工厂类注册为 Bean,并通过 @Qualifier 注解注入指定实现:
@Component
public class OperationFactory {
private final Map<String, Operation> operations;
public OperationFactory(Map<String, Operation> operations) {
this.operations = operations;
}
public Operation getOperation(String type) {
Operation op = operations.get(type);
if (op == null) throw new IllegalArgumentException("未知操作: " + type);
return op;
}
}
// 具体实现类自动注册到 Spring 容器
@Component("add")
public class AddOperation implements Operation { ... }
此方案无需修改工厂类即可新增产品,完美解决开闭原则问题。
对于无状态对象(如运算类),可缓存常用实例避免重复创建:
public class OperationFactory {
private static final Map<String, Operation> CACHE = new ConcurrentHashMap<>();
static {
CACHE.put("add", new AddOperation());
CACHE.put("sub", new SubOperation());
// 其他初始化...
}
public static Operation createOperation(String type) {
return CACHE.getOrDefault(type.toLowerCase(),
() -> { throw new IllegalArgumentException("不支持类型"); });
}
}
将工厂逻辑拆分为策略集合,提升扩展性:
public interface OperationStrategy {
String getType();
Operation create();
}
@Component
public class AddOperationStrategy implements OperationStrategy {
@Override
public String getType() { return "add"; }
@Override
public Operation create() { return new AddOperation(); }
}
@Service
public class OperationFactory {
private final List<OperationStrategy> strategies;
public OperationFactory(List<OperationStrategy> strategies) {
this.strategies = strategies;
}
public Operation create(String type) {
return strategies.stream()
.filter(s -> s.getType().equals(type))
.findFirst()
.map(OperationStrategy::create)
.orElseThrow(() -> new IllegalArgumentException("未知类型: " + type));
}
}
在 Android 中常见于 View 创建:如 TextView 的 fromHtml() 方法,根据 HTML 字符串动态生成对应 Spannable 对象;又如 Gson 的 create() 方法,根据配置返回不同解析器。典型案例如:
public class ViewFactory {
public static TextView createTextView(String text) {
TextView tv = new TextView(context);
tv.setText(text);
tv.setTextSize(16);
return tv;
}
}
因简单工厂是**编码习惯而非设计模式规范**,GoF 未将其纳入 23 种模式。Java 标准库更倾向使用静态工厂方法(如 Collections.unmodifiableList()、EnumSet.of()),而非定义专用工厂类。其本质是“工厂方法模式”的静态化特例。
DI 容器(如 Spring)本质是高级工厂:通过配置文件或注解,将对象创建与依赖关系管理委托给容器。简单工厂可视为 DI 的轻量级替代方案——当项目无需完整 IoC 容器时,可自建简单工厂满足基本解耦需求。
应编写单元测试覆盖所有分支路径,重点验证:
几乎无性能影响!现代 JVM 对 switch 和反射有高度优化。唯一需关注的是:若工厂内含复杂逻辑(如文件读取、网络请求),应将其移出工厂或加入缓存。实际压测中,简单工厂的调用开销通常低于 0.1%。