9-抽象工厂模式示例:造手机
1. 📱 抽象工厂模式示例:造手机
1.1. 🧠 场景设定
制造一部手机通常需要一整套配件,比如:
- 屏幕(Screen)
- 处理器(CPU)
- 系统(OS)
不同品牌的手机有成套的不同配件,例如:
1.1.1. 🍎 Apple 套餐:
- Retina 屏幕
- A 17 芯片
- IOS 系统
1.1.2. 🤖 Samsung 套餐:
- AMOLED 屏幕
- Exynos 芯片
- Android 系统
这就是抽象工厂模式适合的场景 —— 创建一整套“相关产品”的对象。
1.2. 🧱 Step 1:定义产品族接口
interface Screen {
void display();
}
interface CPU {
void process();
}
interface OS {
void boot();
}
1.3. 🔧 Step 2:具体产品实现
// Apple 配件
class AppleScreen implements Screen {
public void display() {
System.out.println("Retina display");
}
}
class AppleCPU implements CPU {
public void process() {
System.out.println("A17 chip processing");
}
}
class IOS implements OS {
public void boot() {
System.out.println("iOS booting");
}
}
// Samsung 配件
class SamsungScreen implements Screen {
public void display() {
System.out.println("AMOLED display");
}
}
class SamsungCPU implements CPU {
public void process() {
System.out.println("Exynos chip processing");
}
}
class AndroidOS implements OS {
public void boot() {
System.out.println("Android booting");
}
}
1.4. 🏭 Step 3:抽象工厂接口
interface PhoneFactory {
Screen createScreen();
CPU createCPU();
OS createOS();
}
1.5. 🏢 Step 4:具体工厂实现
class AppleFactory implements PhoneFactory {
public Screen createScreen() { return new AppleScreen(); }
public CPU createCPU() { return new AppleCPU(); }
public OS createOS() { return new IOS(); }
}
class SamsungFactory implements PhoneFactory {
public Screen createScreen() { return new SamsungScreen(); }
public CPU createCPU() { return new SamsungCPU(); }
public OS createOS() { return new AndroidOS(); }
}
1.6. 🚀 Step 5:客户端使用
public class PhoneStore {
public static void main(String[] args) {
PhoneFactory factory = new AppleFactory(); // 可切换为 SamsungFactory
Screen screen = factory.createScreen();
CPU cpu = factory.createCPU();
OS os = factory.createOS();
screen.display();
cpu.process();
os.boot();
}
}
1.6.1. ✅ 输出结果:
Retina display
A17 chip processing
iOS booting
1.7. 📌 总结
关键词 | 含义 |
---|---|
产品族 | 一整套相关产品(屏幕、CPU、系统) |
抽象工厂 | 提供创建这些产品的统一接口 |
具体工厂 | AppleFactory、SamsungFactory |
抽象工厂的好处:
-
保证创建产品的一致性(成套出现,防止混搭)
-
可扩展性强,支持多个产品族
-
客户端只依赖接口,符合依赖倒置 & 开闭原则
💡 抽象工厂模式不是抽象“类”,而是抽象“如何成套地生产产品”。