首页 > 解决方案 > 从构造函数调用工厂?

问题描述

我正在编写一个程序来管理预订,为此我有一个 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;
       }
}

任何想法如何解决它?谢谢

标签: java

解决方案


关于工厂方法/类的主要(如果不是全部)点是减少或消除直接构造函数调用的需要。

您尝试做的事情在技术上是不可能的。从构造函数中,调用返回与正在构造的方法相同类型的不同方法只能导致 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;
       }
   }
}

推荐阅读