抽象工厂模式(Abstract Factory Pattern)是一种创建型设计模式,它提供了一个接口,用于创建一系列相关或相互依赖的对象,而无需指定它们具体的类。抽象工厂模式是围绕一个超级工厂创建其他工厂的模式。该模式的实现涉及到多个类和对象。
下面是一个抽象工厂模式的 Java 实践案例,假设我们有两种类型的产品(按钮和文本框),并且每种产品有两种不同的风格(Windows 风格和 MacOS 风格)。
步骤1:为每种类型的产品定义接口
1// 按钮产品接口
2public interface Button {
3 void paint();
4}
5
6// 文本框产品接口
7public interface TextBox {
8 void paint();
9}
步骤2:为每种风格的产品实现具体类
1// Windows 风格的按钮
2public class WindowsButton implements Button {
3 @Override
4 public void paint() {
5 System.out.println("Rendering a button in a Windows style.");
6 }
7}
8
9// MacOS 风格的按钮
10public class MacOSButton implements Button {
11 @Override
12 public void paint() {
13 System.out.println("Rendering a button in a MacOS style.");
14 }
15}
16
17// Windows 风格的文本框
18public class WindowsTextBox implements TextBox {
19 @Override
20 public void paint() {
21 System.out.println("Rendering a text box in a Windows style.");
22 }
23}
24
25// MacOS 风格的文本框
26public class MacOSTextBox implements TextBox {
27 @Override
28 public void paint() {
29 System.out.println("Rendering a text box in a MacOS style.");
30 }
31}
步骤3:创建抽象工厂接口
1public interface GUIFactory {
2 Button createButton();
3 TextBox createTextBox();
4}
步骤4:为每种风格实现具体的工厂类
1// Windows 风格的工厂
2public class WindowsFactory implements GUIFactory {
3 @Override
4 public Button createButton() {
5 return new WindowsButton();
6 }
7
8 @Override
9 public TextBox createTextBox() {
10 return new WindowsTextBox();
11 }
12}
13
14// MacOS 风格的工厂
15public class MacOSFactory implements GUIFactory {
16 @Override
17 public Button createButton() {
18 return new MacOSButton();
19 }
20
21 @Override
22 public TextBox createTextBox() {
23 return new MacOSTextBox();
24 }
25}
步骤5:客户端代码使用抽象工厂
1public class Client {
2 private Button button;
3 private TextBox textBox;
4
5 public Client(GUIFactory factory) {
6 button = factory.createButton();
7 textBox = factory.createTextBox();
8 }
9
10 public void paint() {
11 button.paint();
12 textBox.paint();
13 }
14
15 public static void main(String[] args) {
16 Client client;
17
18 // 使用 Windows 风格的工厂
19 client = new Client(new WindowsFactory());
20 client.paint();
21
22 // 使用 MacOS 风格的工厂
23 client = new Client(new MacOSFactory());
24 client.paint();
25 }
26}
在这个例子中,GUIFactory 是一个抽象工厂,它定义了创建一组 GUI 组件的方法。WindowsFactory 和 MacOSFactory 是两个具体的工厂,它们实现了 GUIFactory 并创建对应风格的 GUI 组件。
客户端代码通过抽象工厂接口来创建 GUI 组件,这样无论是 Windows 风格还是 MacOS 风格的 GUI 组件,都不需要修改客户端的逻辑。
抽象工厂模式的优点是,它支持对产品系列的扩展。如果我们想要添加一个新的产品风格(比如 Linux 风格),我们只需要添加一个新的工厂和一组产品类,而不需要修改现有代码。这种模式也有助于保持家族产品的一致性,确保客户端始终同时使用某个家族的所有产品。