摘要
抽象工厂模式(Abstract Factory Pattern)是一种设计模式,它可以帮助我们创建一系列相关或相互依赖的对象,而不需要暴露对象的具体实现细节。它属于创建型模式,与工厂方法模式类似,但它能够创建一系列不同但相关的对象,而不是只创建一个对象。
主体架构
具体做法
在抽象工厂模式中,我们需要定义一个抽象工厂接口,该接口定义了一组可以创建不同对象的方法,而这些对象是属于同一个产品族(Product Family)的。每个具体的工厂类都实现了该接口,并负责创建特定的产品族。
举例
假设我们正在创建一个跨平台的应用程序,需要创建两个组件:一个按钮和一个文本框。在Windows操作系统中,按钮和文本框通常是矩形的,而在MacOS中,按钮和文本框通常是圆形的。我们可以使用抽象工厂模式来创建这两个组件,并且确保它们在不同的操作系统上有不同的外观。
首先,我们需要定义一个抽象工厂接口,例如:
public interface GUIFactory {
Button createButton();
TextBox createTextBox();
}
然后,我们创建两个具体的工厂类,分别用于创建Windows和MacOS的按钮和文本框:
public class WindowsGUIFactory implements GUIFactory {
public Button createButton() {
return new WindowsButton();
}
public TextBox createTextBox() {
return new WindowsTextBox();
}
}
public class MacOSGUIFactory implements GUIFactory {
public Button createButton() {
return new MacOSButton();
}
public TextBox createTextBox() {
return new MacOSTextBox();
}
}
其中,WindowsButton、WindowsTextBox、MacOSButton和MacOSTextBox是具体的产品类,它们实现了Button和TextBox接口,分别表示不同操作系统下的按钮和文本框。
最后,我们可以创建一个应用程序类,该类使用相应的工厂类来创建不同操作系统下的按钮和文本框
public class Application {
public Application(GUIFactory factory) {
Button button = factory.createButton();
TextBox textBox = factory.createTextBox();
// do something with button and textBox
}
}
public class Client {
public static void main(String[] args) {
GUIFactory factory;
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("windows")) {
factory = new WindowsGUIFactory();
} else if (os.contains("mac")) {
factory = new MacOSGUIFactory();
} else {
throw new RuntimeException("Unsupported operating system");
}
Application app = new Application(factory);
}
}
在这个例子中,我们通过使用抽象工厂模式,可以轻松地创建不同操作系统下的组件,并且确保它们的外观是与操作系统相匹配的。