设计模式-抽象工厂模式

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

相关推荐
炎芯随笔8 小时前
【C++】【设计模式】生产者-消费者模型
开发语言·c++·设计模式
workflower15 小时前
使用谱聚类将相似度矩阵分为2类
人工智能·深度学习·算法·机器学习·设计模式·软件工程·软件需求
枣伊吕波18 小时前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式
lalajh18 小时前
论软件设计模式及其应用
设计模式
lgily-122521 小时前
常用的设计模式详解
java·后端·python·设计模式
周努力.2 天前
设计模式之中介者模式
设计模式·中介者模式
yangyang_z2 天前
【C++设计模式之Template Method Pattern】
设计模式
源远流长jerry2 天前
常用设计模式
设计模式
z26373056112 天前
六大设计模式--OCP(开闭原则):构建可扩展软件的基石
设计模式·开闭原则
01空间3 天前
设计模式简述(十八)享元模式
设计模式·享元模式