静态工厂方法或创建方法

发布于 2024-07-16 08:40:38 字数 640 浏览 5 评论 0原文

我想知道这种构造的正确定义:

class A {
 public static A create() {
    return new A();
 }

 private A() {
 }
}

Effective Java 中(项目 1 )和维基百科文章我发现这被称为静态工厂方法< /em> (某种工厂方法)。

但是在阅读 重构模式(第 6 章)时,我遇到了相同的结构称为创建方法。 另外,还有一点需要注意的是,它不应该与工厂方法模式混淆。

真理在哪里?

I am wondering about correct definition for such construction:

class A {
 public static A create() {
    return new A();
 }

 private A() {
 }
}

In Effective Java (Item 1) and on wikipedia article I found that this is called Static Factory Method (some kind of Factory Method).

But during reading of Refactoring to Patterns (Chapter 6) I met the same construction called Creation Method. Also, there is a note that it should not be messed up with a Factory Method pattern.

Where truth is?

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

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

发布评论

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

评论(4

陈甜 2024-07-23 08:40:38

阅读这篇关于工厂方法的讨论

FactoryMethodPatternFactoryMethodCreationMethod .

Have a read of this discussion of Factory Method.

FactoryMethodPattern is different from FactoryMethod or CreationMethod.

放手` 2024-07-23 08:40:38

一种方法是调用无参数方法创建方法和参数化方法(例如通过枚举)-工厂方法。 从某种意义上说,工厂更强大,可以创建不同类型的对象。

如果您使用无参数方法,您必须在其他地方决定调用哪个类的方法。 使用参数化方法,您可以将此逻辑传递给方法本身。 所以后者(工厂)也自行决定创建哪个类对象。

One approach is to call parameterless methods creation methods and parameterized (for example by an enum) - factory methods. In the sence that a factory is more powerful and can create objects of different types.

If you use a parameterless method you have to decide elsewhere which class' method to call. With a parameterized method you pass this logic to the method itself. So the latter (factory) also decides by itself which class object to create.

温馨耳语 2024-07-23 08:40:38

创建方法是创建类实例的静态或非静态方法。
工厂方法是在类层次结构中定义和实现的方法,并且创建具有多态性。

Creation Method is a static or non-static method that creates an instance of a class.
Factory Method is a method defined and implemented in a class hierarchy and the creation is of a polymorphic nature.

美胚控场 2024-07-23 08:40:38

嗯,不同作者之间的术语通常有所不同,所以我不会对此太担心。

然而,我认为“重构模式”警告不要将此称为“工厂方法”,因为有 工厂方法模式。 由于工厂方法模式不仅仅是工厂方法,因此他们提出了不同的名称以避免混淆。

我想您也可以将其称为“简单静态工厂”,但这有点啰嗦(而且不标准)。

Well, terminology often varies between authors, so I wouldn't worry too much about this.

I suppose, however, that "Refactoring to Patterns" warns against calling this a "factory method", because there is the factory method pattern. Since the factory method pattern is more than just a factory method, they propose a different name to avoid confusion.

I guess you could also call it a "simple static factory", but that's a bit wordy (and non-standard).

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