gpt4 book ai didi

java - 静态工厂方法如何返回一个新实例?

转载 作者:行者123 更新时间:2023-11-30 06:23:47 24 4
gpt4 key购买 nike

我在各个地方都读到过,通常建议在公共(public)构造函数上使用静态工厂方法。

优点之一是与构造函数不同,静态工厂方法不会在每次调用时创建新对象。然而,正如我在 this site 上读到的那样, 类的工厂方法

class Employee {
private int _type;
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;

Employee (int type) {
_type = type;
}
}

定义为:

static Employee create(int type) {
return new Employee(type);
}

因此,为了创建一个新实例,我们这样做

Employee eng = Employee.create(Employee.ENGINEER);

我不明白的是,工厂方法不是调用公共(public)构造函数吗?那么它不是重新创建一个新实例吗?

我不太理解的使用静态工厂方法的第二个方面是为什么没有公共(public)/ protected 构造函数的类不能被子类化?

最佳答案

我相信它没有正确实现。在这种情况下,构造函数不应该是 private 吗?拥有 static 工厂方法的全部意义在于禁止直接从其他代码使用构造函数直接访问以创建实例。假设,你的类提供数据库连接,因为我们知道连接是资源密集型的,我们不应该随意创建连接,静态工厂用于请求连接对象。工厂方法检查池中是否有空闲连接对象并将其返回。可重用性是这里的重要概念,它由静态工厂方法实现。

另一点是它抽象掉了对象的实例化。通常,当您知道需要实现某个接口(interface)的类的新实例但不知道实现类时,工厂很有用。

该链接中提供的代码只是其工作原理的示例,但并不是一个很好的示例。进一步阅读:

The most obvious motivation for Replace Constructor with Factory Method comes with replacing a type code with subclassing. You have an object that often is created with a type code but now needs subclasses. The exact subclass is based on the type code. However, constructors can only return an instance of the object that is asked for. So you need to replace the constructor with a factory method.

回到你的问题:

What I don't understand is, isn't the factory method invoking the public constructor? So isn't it creating a new instance all over again?

是的,可能不应该。

I don't quite understand is why can classes without public / protected constructors not be subclassed?

即使是具有默认访问权限的构造函数,即没有访问修饰符的构造函数也可以被子类化。但是子类应该是包的一部分。请记住,一旦您对一个类进行子类化,在创建子类的对象时,子类构造函数隐式/显式必须调用父类(super class)构造函数。现在,如果子类构造函数无法访问父类(super class)构造函数,因为它被标记为 private,则实例化失败。因此,子类化没有意义。

推荐阅读:

  1. Consider static factory methods instead of constructors - Josh Bloch
  2. What are static factory methods in Java?

关于java - 静态工厂方法如何返回一个新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17905250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com