My App

抽象工厂

Abstract Factory — 创建一组相关对象的"工厂的工厂"

一句话理解

提供一个接口,用来创建一系列相关的对象,而不需要指定它们的具体类。

和工厂方法的区别

工厂方法抽象工厂
创建一种产品一族产品(多种相关产品)
工厂数量每个产品一个工厂一个工厂创建一整套产品

解决什么问题

当系统需要创建多种相互关联的对象时(比如一套 UI 组件),如果直接 new,每次切换风格就要改很多地方。抽象工厂让你一次性切换整套实现

怎么写

以"跨平台 UI 组件"为例 —— 不同操作系统需要不同风格的按钮和输入框:

// 抽象产品
public interface Button { void render(); }
public interface Input  { void render(); }

// Windows 风格
public class WinButton implements Button {
    public void render() { System.out.println("Windows 风格按钮"); }
}
public class WinInput implements Input {
    public void render() { System.out.println("Windows 风格输入框"); }
}

// Mac 风格
public class MacButton implements Button {
    public void render() { System.out.println("Mac 风格按钮"); }
}
public class MacInput implements Input {
    public void render() { System.out.println("Mac 风格输入框"); }
}

// 抽象工厂:一个工厂能创建一整套组件
public interface UIFactory {
    Button createButton();
    Input createInput();
}

// 具体工厂
public class WinUIFactory implements UIFactory {
    public Button createButton() { return new WinButton(); }
    public Input createInput()   { return new WinInput(); }
}
public class MacUIFactory implements UIFactory {
    public Button createButton() { return new MacButton(); }
    public Input createInput()   { return new MacInput(); }
}
// 使用:只需要换一个工厂,整套 UI 全部切换
UIFactory factory = new MacUIFactory();
factory.createButton().render();  // Mac 风格按钮
factory.createInput().render();   // Mac 风格输入框

使用场景

  • 跨数据库支持(MySQL 工厂生产 MySQL 的 Connection/Statement/ResultSet)
  • 主题系统(暗色主题 / 亮色主题的一整套组件)
  • 跨平台应用的 UI 组件

On this page