工厂方法模式

工厂生产组件的接口都是抽象的,具体生产类型,由 工厂类型决定

图解

在这里插入图片描述

定义一个按钮组件

public interface Button {

    void paint();

}

组件实现类

mac

public class MacOsButton implements Button {
    @Override
    public void paint() {
        System.out.println("You have created MacOSButton.");
    }
}

window

public class WindowsButton implements Button {
    @Override
    public void paint() {
        System.out.println("You have created WindowsButton.");
    }
}

工厂抽象接口

public interface GUIFactory {
    Button createButton();
}

工厂实现

mac

public class MacOSFactory implements GUIFactory{
    @Override
    public Button createButton() {
        return new MacOsButton();
    }
}

windows

public class WindowsFactory implements GUIFactory {
    @Override
    public Button createButton() {
        return new WindowsButton();
    }
}

应用

public class Application {
    private Button button;

    public Application(GUIFactory factory) {
        button = factory.createButton();
    }

    public void paint() {
        button.paint();
    }
}

测试类

public class Demo {
    private static Application configureApplication() {
        Application app;
        GUIFactory factory;
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("mac")) {
            factory = new MacOSFactory();
            app = new Application(factory);
        } else {
            factory = new WindowsFactory();
            app = new Application(factory);
        }
        return app;
    }

    public static void main(String[] args) {
        Application app = configureApplication();
        app.paint();
    }
}

更多推荐