工厂方法 VS 工厂对象

发布于 2025-01-01 10:48:18 字数 663 浏览 4 评论 0原文

据我了解,工厂方法是简单工厂,工厂对象是抽象工厂? 并且:

-工厂方法(简单工厂):

public class SimplePizzaFactory {
    public static final int CHEESE = 1;
    public static final int PEPPERONI = 2;
    public static final int VEGGIE = 3;

    public static Pizza createPizza(int type) {
        Pizza pizza = null;

        if (type == CHEESE) {
            pizza = new CheesePizza();
        } else if (type == PEPPERONI ) {
            pizza = new PepperoniPizza();
        } else if (type == VEGGIE ) {
            pizza = new VeggiePizza();
        }

        return pizza;
    }
}

工厂对象(抽象工厂)

:?

我说得对吗?

工厂模式有多少种实现,它们有什么区别?

As I understand Factory Method is Simple Factory and Factory Object is Abstract Factory?
And:

-Factory Method (Simple Factory):

public class SimplePizzaFactory {
    public static final int CHEESE = 1;
    public static final int PEPPERONI = 2;
    public static final int VEGGIE = 3;

    public static Pizza createPizza(int type) {
        Pizza pizza = null;

        if (type == CHEESE) {
            pizza = new CheesePizza();
        } else if (type == PEPPERONI ) {
            pizza = new PepperoniPizza();
        } else if (type == VEGGIE ) {
            pizza = new VeggiePizza();
        }

        return pizza;
    }
}

Factory Object(Abstract Factory):

?

Am I right?

How much are there realizations of Factory patterns and what is their difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鲸落 2025-01-08 10:48:18

不。工厂方法是不需要任何状态的工厂。工厂类本身就是一个类 - 它具有状态以及改变该状态的方法。最后,您调用 .create() 方法,它使用其当前状态创建不同类型的新对象。

抽象工厂是另一回事——同一个抽象概念有多个工厂实现。 wikipedia 示例 是关于 e GUIFactory - 这是一个抽象工厂,它有两个实现:WinFactoryOSXFactory。客户端代码不知道它正在使用哪个实现 - 它只知道工厂创建 Button 实例。这使得无论操作系统如何都可以编写相同的代码。

No. A factory-method is a factory that does not require any state. A factory class is a class itself - it has state, and methods that alter that state. In the end you call the .create() method, and it uses its current state to create a new object of a different type.

Abstract factory is a different thing - there you have multiple factory implementations of the same abstract concept. The wikipedia example is about e GUIFactory - this is an abstract factory, which has two implementations: WinFactory and OSXFactory. The client code does not know which implementation it is using - it just knows the factory creates Button instances. Which make it possible to write the same code regardless of the OS.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文