设计模式-抽象工厂模式

在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 是它的具体实现。客户端程序通过具体工厂创建具体产品。

相关推荐
杯子不吃紫菜1 天前
LangGraph 体系实战(下):中断恢复、流式、子图与设计模式
单片机·嵌入式硬件·设计模式
是2的10次方啊1 天前
设计模式与生活⑳:楼里的事都找前台,你就再没见过师傅
设计模式
是2的10次方啊2 天前
设计模式与生活⑲:投影连不上,别急着换投影仪
设计模式
cjz38993 天前
规则树:把一百行if-else拆成一棵树
设计模式
Adellle3 天前
设计模式指南 (Java 版) ㊁
java·开发语言·设计模式
是2的10次方啊3 天前
设计模式与生活⑱:工资还没焐热,账单已经凑成一摞
设计模式
百思不得小李4 天前
一个复杂的动态表单是如何实现的
前端·设计模式
爱你真是太好了4 天前
上下文组成以及如何压缩
设计模式
freejackman4 天前
【工程化】从“单兵作战”到“多引擎架构”:基于门面模式的重构实战
大数据·数据库·hive·sql·测试工具·设计模式·架构
Java成神之路-4 天前
从 if-else 到优雅解耦:策略 / 适配器 / 组合模式全流程实战
设计模式