设计模式-抽象工厂模式

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

相关推荐
江米小枣tonylua13 小时前
从红绿灯到方向盘:TDD 在 AI 时代的新角色
前端·设计模式·ai编程
nnsix13 小时前
设计模式 - 工厂模式 笔记
笔记·设计模式
洛水水18 小时前
结构性设计模式详解
c++·设计模式
多加点辣也没关系19 小时前
设计模式-策略模式
java·设计模式·策略模式
雪度娃娃19 小时前
结构型设计模式——代理模式
java·c++·设计模式·系统安全·代理模式
蜡笔小马1 天前
06.C++设计模式-装饰模式
c++·设计模式·装饰器模式
悟05151 天前
设计模式-策略模式
设计模式·策略模式
UXbot1 天前
一人独立交付 UI + 前端:AI 驱动 UI 设计工具的五大功能模块深度评测
前端·低代码·ui·设计模式·交互
蜡笔小马2 天前
07.C++设计模式-组合模式
c++·设计模式·组合模式