设计模式-抽象工厂模式

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

相关推荐
木斯佳15 小时前
HarmonyOS 6 三方SDK对接:从半接模式看Share Kit原理——系统分享的运行机制与设计理念
设计模式·harmonyos·架构设计·分享·半接模式
yydonk15 小时前
像 Agent 一样思考:从 Claude Code 架构演进看 AI Agent 工具设计
设计模式
Jackson_Li18 小时前
大多数人对 Claude Code Skills 的理解,在第一步就错了
人工智能·设计模式
似水明俊德21 小时前
13-C#.Net-设计模式六大原则-学习笔记
笔记·学习·设计模式·c#·.net
wangchunting1 天前
Java设计模式
java·单例模式·设计模式
孟陬2 天前
国外技术周刊 #3:“最差程序员”带动高效团队、不写代码的创业导师如何毁掉创新…
前端·后端·设计模式
砍光二叉树2 天前
【设计模式】结构型-代理模式
设计模式·系统安全·代理模式
新缸中之脑2 天前
AI智能体五大设计模式
人工智能·机器学习·设计模式
砍光二叉树2 天前
【设计模式】结构型-装饰器模式
设计模式·装饰器模式
han_2 天前
JavaScript设计模式(三):代理模式实现与应用
前端·javascript·设计模式