设计模式-抽象工厂模式

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

相关推荐
回忆2012初秋7 小时前
工厂方法模式完整实现:GPS转换
设计模式·工厂方法模式
胡志辉的博客10 小时前
多智能体协作,不是多开几个 Agent:从中介者模式看 OpenClaw 和 Hermes Agent
人工智能·设计模式·ai·agent·中介者模式·openclaw·herman
shark222222210 小时前
能懂!基于Springboot的用户增删查改(三层设计模式)
spring boot·后端·设计模式
014-code11 小时前
日志规范:怎么写才不算写废话
java·开发语言·设计模式·日志
楼田莉子12 小时前
同步/异步日志系统:日志落地模块\日志器模块\异步日志模块
linux·服务器·c++·学习·设计模式
kyriewen1119 小时前
代码写成一锅粥?这5种设计模式让你的项目“起死回生”
前端·javascript·设计模式·typescript·ecmascript·html5
kyriewen19 小时前
代码写成一锅粥?这5种设计模式让你的项目“起死回生”
前端·javascript·设计模式
两年半的个人练习生^_^20 小时前
每日一学:设计模式之原型模式
java·开发语言·设计模式·原型模式
断眉的派大星1 天前
工厂模式(Factory Pattern)完整详解
python·设计模式
AI大法师2 天前
复盘 TikTok 品牌升级:动态品牌系统应该怎么理解和落地
大数据·人工智能·设计模式