设计模式-抽象工厂模式

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

相关推荐
Leo来编程4 小时前
设计模式1-单例模式
单例模式·设计模式
危险库4 小时前
单例模式:确保一个类只有一个实例【设计模式】
javascript·单例模式·设计模式
已读不回1437 小时前
设计模式-策略模式
前端·算法·设计模式
饕餮争锋12 小时前
设计模式笔记_行为型_访问者模式
笔记·设计模式·访问者模式
写bug写bug1 天前
你真的会用枚举吗
java·后端·设计模式
哆啦code梦1 天前
趣谈设计模式之策略模式-比特咖啡给你一杯满满的情绪价值,让您在数字世界里”畅饮“
设计模式·策略模式
华仔啊1 天前
别学23种了!Java项目中最常用的6个设计模式,附案例
java·后端·设计模式
Keya1 天前
MacOS端口被占用的解决方法
前端·后端·设计模式
已读不回1431 天前
设计模式-单例模式
前端·设计模式
long3162 天前
构建者设计模式 Builder
java·后端·学习·设计模式