Method in Java to get an object instance

  1. Public constructor
Boolean bool = new Boolean("ture");
public Boolean(boolean value) {
    this.value = value;
}
Copy the code
  1. Static factory method
Boolean bool = Boolean.valueOf("ture");
public static Boolean valueOf(String s) {
    return parseBoolean(s) ? TRUE : FALSE;
}
Copy the code

Advantages of the static factory approach

  1. Static factory methods can have their own names.
  2. Static factory methods can return the same object for repeated calls without creating a new instance for each call;
// TRUE and FALSE are static immutable properties of Boolean classes
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
Copy the code
  1. Static factory methods can return objects of any subtype of the original return type;
  2. .

Disadvantages of the static factory approach

Static factory methods are hard to spot by programmers, so here are some common names:

  1. From-type conversion method
Date date = Date.from(instant);
Copy the code
  1. Of – aggregation method
Set<Rank> faceCards = EnumSet.of(JACK, QUEUE, KING);
Copy the code
  1. The ValueOf – common
String str1 = String.valueOf(123);
Integer int1 = Integer.valueOf("123");
Long long1 = Long.valueOf("123");
Copy the code
  1. Instance or getInstance – The returned instance is described by the method’s arguments
  2. Create or newInstance – returns a newInstance per call
  3. .

Conclusion: Static factory approach is more suitable, remember the first reaction is to provide public constructor, not static factory!