Hiding a constructor behind a static creator method?

前端 未结 9 1594
我在风中等你
我在风中等你 2021-01-04 00:47

I\'ve recently discovered an interesting way to create a new instance of an object in Google Guava and Project Lombok: Hide a constructor behind a static creator method. Thi

9条回答
  •  伪装坚强ぢ
    2021-01-04 01:09

    Unlike constructors, static methods can have method names. Here's a recent class I wrote where this was useful:

    /**
     * A number range that can be min-constrained, max-constrained, 
     * both-constrained or unconstrained.
     */
    
    public class Range {
      private final long min;
      private final long max;
      private final boolean hasMin;
      private final boolean hasMax;
    
      private Range(long min, long max, boolean hasMin, boolean hasMax) {
        // ... (private constructor that just assigns attributes)
      }
    
      // Static factory methods
    
      public static Range atLeast (long min) {
        return new Range(min, 0, true, false);
      }
    
      public static Range atMost (long max) {
        return new Range(0, max, false, true);
      }
    
      public static Range between (long min, long max) {
        return new Range(min, max, true, true);
      }
    
      public static Range unconstrained () {
        return new Range (0, 0, false, false);
      }
    }
    

    You couldn't do this using just constructors, as atLeast and atMost would have the exact same signature (they both take one long).

提交回复
热议问题