什么是工厂模式?
工厂模式是一种创建对象的设计模式,它把对象的创建过程封装起来,客户端只需要告诉工厂"我要什么",工厂就会返回相应的对象。
就像餐厅点餐:
- 你告诉服务员"我要一份宫保鸡丁"
- 厨师在后厨制作(你不需要知道怎么做)
- 服务员把做好的菜端给你
主要解决什么问题?
工厂模式主要解决以下问题:
- 对象创建复杂:对象的创建需要复杂逻辑(如读取配置、依赖组装)
- 解耦客户端:客户端代码不依赖具体类,只依赖抽象接口
- 集中管理:统一管理对象的创建和生命周期
- 避免重复代码:将创建逻辑集中在一处,避免到处写
new
何时使用工厂模式?
当你遇到以下场景时,考虑使用工厂模式:
- 需要根据不同条件创建不同对象(如不同支付方式)
- 对象的创建过程复杂(需要初始化、设置参数等)
- 希望隐藏创建细节(客户端不关心对象怎么来的)
- 需要统一管理对象的创建(如连接池、线程池)
工厂模式的优点
- 解耦:客户端和具体实现类解耦
- 可扩展:新增产品只需添加新类,符合开闭原则
- 复用:创建逻辑可以复用
- 统一管理:对象的创建和配置集中管理
- 测试友好:可以轻松替换mock对象
工厂模式的缺点
- 增加类数量:每增加一个产品可能需要增加一个工厂类
- 复杂度提升:引入抽象层次,增加理解难度
- 过度设计:简单场景用工厂反而复杂
代码示例:通知系统
让我们用一个通知系统的例子来演示工厂模式的三种变体。
1. 简单工厂模式(静态工厂)
// 产品接口
interface Notification {
void send(String message);
}
// 具体产品:邮件通知
class EmailNotification implements Notification {
@Override
public void send(String message) {
System.out.println("发送邮件: " + message);
// 实际的邮件发送逻辑
}
}
// 具体产品:短信通知
class SMSNotification implements Notification {
@Override
public void send(String message) {
System.out.println("发送短信: " + message);
// 实际的短信发送逻辑
}
}
// 具体产品:微信通知
class WeChatNotification implements Notification {
@Override
public void send(String message) {
System.out.println("发送微信: " + message);
// 实际的微信发送逻辑
}
}
// 简单工厂
class NotificationFactory {
public static Notification createNotification(String type) {
switch (type.toLowerCase()) {
case "email":
return new EmailNotification();
case "sms":
return new SMSNotification();
case "wechat":
return new WeChatNotification();
default:
throw new IllegalArgumentException("未知的通知类型: " + type);
}
}
}
// 客户端使用
public class SimpleFactoryDemo {
public static void main(String[] args) {
// 从配置文件读取通知类型
String notificationType = "email";
Notification notification = NotificationFactory.createNotification(notificationType);
notification.send("Hello, World!");
// 输出:发送邮件: Hello, World!
}
}
特点:一个工厂生产所有产品,简单直接,但扩展性差。
2. 工厂方法模式
// 抽象工厂接口
interface NotificationFactory {
Notification createNotification();
}
// 具体工厂:邮件工厂
class EmailNotificationFactory implements NotificationFactory {
@Override
public Notification createNotification() {
// 可以在这里进行复杂的初始化
System.out.println("初始化邮件服务...");
// 配置SMTP服务器、认证信息等
return new EmailNotification();
}
}
// 具体工厂:短信工厂
class SMSNotificationFactory implements NotificationFactory {
@Override
public Notification createNotification() {
System.out.println("初始化短信服务...");
// 配置短信网关、模板等
return new SMSNotification();
}
}
// 具体工厂:微信工厂
class WeChatNotificationFactory implements NotificationFactory {
@Override
public Notification createNotification() {
System.out.println("初始化微信服务...");
// 配置微信API、密钥等
return new WeChatNotification();
}
}
// 客户端使用
public class FactoryMethodDemo {
public static void main(String[] args) {
// 根据配置选择工厂
NotificationFactory factory = getNotificationFactory("sms");
Notification notification = factory.createNotification();
notification.send("Hello, Factory Method!");
}
private static NotificationFactory getNotificationFactory(String type) {
switch (type.toLowerCase()) {
case "email":
return new EmailNotificationFactory();
case "sms":
return new SMSNotificationFactory();
case "wechat":
return new WeChatNotificationFactory();
default:
throw new IllegalArgumentException("未知的通知类型");
}
}
}
特点:每个产品有自己的工厂,符合开闭原则,扩展性好。
3. 抽象工厂模式(产品族)
// 抽象产品1:通知发送器
interface NotificationSender {
void send(String message);
}
// 抽象产品2:通知记录器
interface NotificationLogger {
void log(String message);
}
// 抽象产品3:通知模板
interface NotificationTemplate {
String format(String message);
}
// 邮件产品族
class EmailSender implements NotificationSender {
@Override
public void send(String message) {
System.out.println("邮件发送: " + message);
}
}
class EmailLogger implements NotificationLogger {
@Override
public void log(String message) {
System.out.println("邮件日志: " + message);
}
}
class EmailTemplate implements NotificationTemplate {
@Override
public String format(String message) {
return "[邮件] " + message;
}
}
// 短信产品族
class SMSSender implements NotificationSender {
@Override
public void send(String message) {
System.out.println("短信发送: " + message);
}
}
class SMSLogger implements NotificationLogger {
@Override
public void log(String message) {
System.out.println("短信日志: " + message);
}
}
class SMSTemplate implements NotificationTemplate {
@Override
public String format(String message) {
return "[短信] " + message;
}
}
// 抽象工厂:通知产品族工厂
interface NotificationFactoryV2 {
NotificationSender createSender();
NotificationLogger createLogger();
NotificationTemplate createTemplate();
}
// 邮件工厂
class EmailNotificationFactoryV2 implements NotificationFactoryV2 {
@Override
public NotificationSender createSender() {
return new EmailSender();
}
@Override
public NotificationLogger createLogger() {
return new EmailLogger();
}
@Override
public NotificationTemplate createTemplate() {
return new EmailTemplate();
}
}
// 短信工厂
class SMSNotificationFactoryV2 implements NotificationFactoryV2 {
@Override
public NotificationSender createSender() {
return new SMSSender();
}
@Override
public NotificationLogger createLogger() {
return new SMSLogger();
}
@Override
public NotificationTemplate createTemplate() {
return new SMSTemplate();
}
}
// 客户端使用
public class AbstractFactoryDemo {
public static void main(String[] args) {
// 使用邮件产品族
NotificationFactoryV2 emailFactory = new EmailNotificationFactoryV2();
NotificationSender emailSender = emailFactory.createSender();
NotificationLogger emailLogger = emailFactory.createLogger();
NotificationTemplate emailTemplate = emailFactory.createTemplate();
String message = "Hello, World!";
String formattedMessage = emailTemplate.format(message);
emailSender.send(formattedMessage);
emailLogger.log(formattedMessage);
System.out.println("---");
// 使用短信产品族
NotificationFactoryV2 smsFactory = new SMSNotificationFactoryV2();
NotificationSender smsSender = smsFactory.createSender();
NotificationLogger smsLogger = smsFactory.createLogger();
NotificationTemplate smsTemplate = smsFactory.createTemplate();
formattedMessage = smsTemplate.format(message);
smsSender.send(formattedMessage);
smsLogger.log(formattedMessage);
}
}
特点:生产一系列相关的产品(产品族),保证产品之间的兼容性。
4. 使用反射的通用工厂
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
// 通用工厂(使用反射)
class GenericFactory {
private static final Map<String, Class<? extends Notification>> registry = new HashMap<>();
// 注册产品类
public static void register(String type, Class<? extends Notification> clazz) {
registry.put(type.toLowerCase(), clazz);
}
// 创建产品
public static Notification create(String type, Object... args) {
try {
Class<? extends Notification> clazz = registry.get(type.toLowerCase());
if (clazz == null) {
throw new IllegalArgumentException("未注册的类型: " + type);
}
// 根据参数选择构造函数
if (args.length == 0) {
return clazz.getDeclaredConstructor().newInstance();
} else {
// 处理带参数的构造函数
Class<?>[] paramTypes = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
paramTypes[i] = args[i].getClass();
}
Constructor<? extends Notification> constructor = clazz.getConstructor(paramTypes);
return constructor.newInstance(args);
}
} catch (Exception e) {
throw new RuntimeException("创建对象失败", e);
}
}
}
// 新增产品:钉钉通知
class DingTalkNotification implements Notification {
private String webhook;
public DingTalkNotification() {
this.webhook = "default-webhook";
}
public DingTalkNotification(String webhook) {
this.webhook = webhook;
}
@Override
public void send(String message) {
System.out.println("发送钉钉消息到 " + webhook + ": " + message);
}
}
// 客户端使用
public class GenericFactoryDemo {
public static void main(String[] args) {
// 注册产品
GenericFactory.register("email", EmailNotification.class);
GenericFactory.register("sms", SMSNotification.class);
GenericFactory.register("dingtalk", DingTalkNotification.class);
// 无参创建
Notification email = GenericFactory.create("email");
email.send("无参创建");
// 有参创建
Notification dingtalk = GenericFactory.create("dingtalk", "https://oapi.dingtalk.com/robot/send");
dingtalk.send("有参创建");
}
}
5. Spring框架中的工厂模式
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;
// Spring FactoryBean示例
@Component
class NotificationFactoryBean implements FactoryBean<Notification> {
private String type;
private String config;
// 通过配置文件注入
public void setType(String type) {
this.type = type;
}
public void setConfig(String config) {
this.config = config;
}
@Override
public Notification getObject() throws Exception {
switch (type) {
case "email":
EmailNotification email = new EmailNotification();
// 根据config配置邮件
return email;
case "sms":
SMSNotification sms = new SMSNotification();
// 根据config配置短信
return sms;
default:
throw new IllegalArgumentException("未知类型");
}
}
@Override
public Class<?> getObjectType() {
return Notification.class;
}
@Override
public boolean isSingleton() {
return true; // 单例模式
}
}
实际应用场景
工厂模式在Java中的经典应用:
-
Spring IoC容器:BeanFactory根据配置创建对象
BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml"); UserService userService = factory.getBean(UserService.class); -
日志框架:LoggerFactory创建Logger
Logger logger = LoggerFactory.getLogger(MyClass.class); -
JDBC:DriverManager创建Connection
Connection conn = DriverManager.getConnection(url, username, password); -
线程池:Executors创建线程池
ExecutorService executor = Executors.newFixedThreadPool(10); -
Java标准库:Calendar.getInstance()、NumberFormat.getInstance()
三种工厂模式的对比
| 模式 | 特点 | 适用场景 | 开闭原则 |
|---|---|---|---|
| 简单工厂 | 一个工厂生产所有产品 | 产品种类少且固定 | ❌ 违反 |
| 工厂方法 | 每个产品有自己的工厂 | 产品可能扩展 | ✅ 符合 |
| 抽象工厂 | 生产产品族(多个相关产品) | 需要配套产品 | ✅ 符合 |
选择建议
- 产品种类少且稳定 → 简单工厂
- 产品种类可能扩展 → 工厂方法
- 需要配套产品 → 抽象工厂
- 对象创建简单 → 直接
new就好,别过度设计
总结
工厂模式的核心思想是:将对象的创建和使用分离。它就像现实生活中的工厂一样,你只需要告诉工厂你要什么,工厂负责生产,你只管使用。
关键点:
- 简单工厂:一个工厂生产所有产品
- 工厂方法:每个产品有自己的工厂
- 抽象工厂:生产一系列相关产品
3201



被折叠的 条评论
为什么被折叠?



