java - 从构造函数调用工厂?
问题描述
我正在编写一个程序来管理预订,为此我有一个 Reservation 类和一个 ReservationFactory 类。
我试图使用工厂创建一个新的预订,但我遇到了这个问题:
“无法从类型 ReservationFactory 对非静态方法 getReservation() 进行静态引用”
public class Reservation {
public Reservation() {
ReservationFactory.getReservation();
}
public Reservation(int code) {
this.code = code;
}
}
class ReservaFactory {
public Reservation getReservation() {
Reservation r = new Reservation(this.getCode());
return r;
}
public int getCode() {
return this.code;
}
}
任何想法如何解决它?谢谢
解决方案
关于工厂方法/类的主要(如果不是全部)点是减少或消除直接构造函数调用的需要。
您尝试做的事情在技术上是不可能的。从构造函数中,调用返回与正在构造的方法相同类型的不同方法只能导致 2 个对象,或预期的异常,或堆栈溢出错误(我可能在这里遗漏了一些结果,但我可以'不认为任何是可取的)。
使用工厂的替代模式包括:
public class Reservation {
//Hide the constructor
private Reservation() {
}
private Reservation(int code) {
this.code = code;
}
//Use a factory method in the same class
public static Reservation instance(int code) {
Reservation r = new Reservation();
r.code = code;
return r;
}
//A builder class, which could also be declared externally
public static class Builder {
//optional parameter
private int code;
public Reservation getReservation() {
return new Reservation(this.code());
}
//A "setter" enabling fluent API
public Builder code(int code) {
this.code = code;
return this;
}
}
}
推荐阅读
- sql-server - 关于 sp_executesql 的错误
- flutter - 有没有我可以使用的文件选择器。我尝试了一些,但他们没有工作
- python - 如何从列表中修复“TypeError:'str' object is not callable”
- docker - Docker 容器自动删除 - Bamboo
- java - 是否可以从 Map 制作 String[][]
使用流 API? - python - 如何在 PyCuda 中使用 tex2D?
- javascript - 如何从文件夹加载 html 文件并将它们显示为本地网页上的链接
- javascript - 通过 JavaScript 创建自动计算
- docker - 如何使用 kubectl 补丁更改 kubernetes 容器的端口?
- android - 如何从底部导航视图打开活动