Java工厂模式解析:三种实现与最佳实践

精心整理了最新的面试资料和简历模板,有需要的可以自行获取

点击前往百度网盘获取
点击前往夸克网盘获取


一、模式概述

工厂模式(Factory Pattern)是创建型设计模式中最常用的模式之一,其核心思想是通过工厂类封装对象的创建过程,实现创建逻辑与使用逻辑的解耦。根据抽象程度不同,工厂模式可分为三种典型实现:

  1. 简单工厂模式(静态工厂)
  2. 工厂方法模式(多态工厂)
  3. 抽象工厂模式(产品族工厂)

二、简单工厂模式

实现代码

// 产品接口
interface Notification {
    void send();
}

// 具体产品
class SMSNotification implements Notification {
    @Override
    public void send() {
        System.out.println("Sending SMS notification");
    }
}

class EmailNotification implements Notification {
    @Override
    public void send() {
        System.out.println("Sending Email notification");
    }
}

// 简单工厂
class NotificationFactory {
    public static Notification createNotification(String type) {
        switch (type.toLowerCase()) {
            case "sms": return new SMSNotification();
            case "email": return new EmailNotification();
            default: throw new IllegalArgumentException("Invalid type");
        }
    }
}

// 使用示例
public class Client {
    public static void main(String[] args) {
        Notification sms = NotificationFactory.createNotification("sms");
        sms.send(); // Output: Sending SMS notification
    }
}

特点分析

  • 优点:快速实现对象创建逻辑的集中管理
  • 缺点:违反开闭原则,新增产品类型需要修改工厂类
  • 适用场景:产品类型较少且不频繁变化的场景

三、工厂方法模式

类结构

// 抽象创建者
abstract class NotificationCreator {
    public abstract Notification createNotification();
    
    public void sendNotification() {
        Notification notification = createNotification();
        notification.send();
    }
}

// 具体创建者
class SMSNotificationCreator extends NotificationCreator {
    @Override
    public Notification createNotification() {
        return new SMSNotification();
    }
}

class EmailNotificationCreator extends NotificationCreator {
    @Override
    public Notification createNotification() {
        return new EmailNotification();
    }
}

优势对比

  1. 符合开闭原则:新增产品只需添加新工厂类
  2. 实现多态:通过继承体系实现不同的创建逻辑
  3. 更易扩展:支持产品创建的复杂初始化过程

四、抽象工厂模式

产品族实现

// 抽象工厂
interface GUIFactory {
    Button createButton();
    Menu createMenu();
}

// 具体工厂
class WindowsFactory implements GUIFactory {
    public Button createButton() {
        return new WindowsButton();
    }
    
    public Menu createMenu() {
        return new WindowsMenu();
    }
}

class MacOSFactory implements GUIFactory {
    public Button createButton() {
        return new MacOSButton();
    }
    
    public Menu createMenu() {
        return new MacOSMenu();
    }
}

核心特征

  • 创建对象家族而非单个产品
  • 保证产品之间的兼容性
  • 更适合复杂系统的基础设施建设

五、模式对比与应用场景

模式类型 创建目标 扩展方向 典型应用场景
简单工厂 单一产品 修改工厂类 配置驱动的对象创建
工厂方法 单一产品 增加子类 框架组件初始化
抽象工厂 产品族 增加接口实现 跨平台UI组件库

六、实际应用案例

  1. Spring框架:BeanFactory和ApplicationContext
  2. 日志框架:LoggerFactory创建不同日志实现
  3. JDBC驱动:DriverManager获取数据库连接

七、最佳实践建议

  1. 优先使用工厂方法模式保证扩展性
  2. 当存在产品族需求时升级到抽象工厂
  3. 配合单例模式优化工厂实例创建
  4. 使用枚举类型强化简单工厂的类型安全
// 枚举优化示例
enum NotificationType {
    SMS(SMSNotification::new),
    EMAIL(EmailNotification::new);

    private final Supplier<Notification> constructor;

    NotificationType(Supplier<Notification> constructor) {
        this.constructor = constructor;
    }

    public Notification create() {
        return constructor.get();
    }
}

八、总结

工厂模式通过封装对象创建过程,有效降低了系统的耦合度。在实际开发中:

  • 80%的场景可以使用工厂方法模式解决
  • 15%的复杂场景需要抽象工厂模式
  • 5%的简单场景可采用简单工厂模式

正确使用工厂模式可以使代码更符合SOLID原则,特别是在大型项目和维护周期长的系统中,其优势会更加明显。

你可能感兴趣的:(提升自己,java,开发语言)