在Java中,抽象工厂模式提供了一种方式,可以封装一组具有共同主题的工厂。以下是一个简单的Java实现:
// 抽象产品
interface Button {
void paint();
}
interface GUIFactory {
Button createButton();
}
// 具体产品
class WinButton implements Button {
public void paint() {
System.out.println("Windows Button");
}
}
class OSXButton implements Button {
public void paint() {
System.out.println("OSX Button");
}
}
// 具体工厂
class WinFactory implements GUIFactory {
public Button createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public Button createButton() {
return new OSXButton();
}
}
// 客户端代码
public class Application {
private GUIFactory factory;
private Button button;
public Application(GUIFactory factory) {
this.factory = factory;
this.button = factory.createButton();
}
public void paint() {
button.paint();
}
public static void main(String[] args) {
Application application;
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
application = new Application(new WinFactory());
} else {
application = new Application(new OSXFactory());
}
application.paint();
}
}
在这个例子中,GUIFactory 是抽象工厂,WinFactory 和 OSXFactory 是它的具体实现。Button 是抽象产品,WinButton 和 OSXButton 是它的具体实现。客户端程序通过具体工厂创建具体产品。