Consider static factory methods instead of constructors

  • One advantage of static factory methods is that, unlike constructors, they have names – ex: BigInteger(int, int, Random) – probably returns a prime number, it is much readable BigInteger.probabluPrime()
  • Static factory methods, unlike constructors, they are not required to create a new object each they’re invoked.
  • Static factory methods, unlinke constructors, can return an object of any subtype of their return type. ex: Collections.[emptyList, unmodifiableMap…]. It may be used when writing service provider framework.
//Servive provider framework sketch
//Service interface
public interface Service {
  //Servicce specific methods
}

//Service provider interface
public interface Provider {
  Service newService();
}

//Noninstantiable class for service registration and access
public class Services {
  private Services() { } //Prevents instantiation
  //Maps service names to services
  private static final Map providers = new ConcurrentHashMap<>();
  private static final String DEFAULT_PROVIDER_NAME = "";

  //Provider registration API
  public static void registerDefaultProvider(Provider provider) {
    registerProvider(DEFAULT_PROVIDER_NAME, provider);
  }
  public static void registerProvider(String name, Provider provider) {
    providers.put(name, provider);
  }

  //Servive access API
  public static Service newInstance() {
    return newInstance(DEFAULT_PROVIDER_NAME);
  }
  public static Service newInstance(String name) {
    Provider provider = providers.get(name);
    if (provider == null) {
      throw new IllegalArgumentException("No provider registered with name: " + name );

    return p.newService();
  }
}
  • Static factory methods can be used to reduce the verbosity of creating parameterized type instances.

Map map = new HashMap<>();

public static  HashMap newInstance() {
  return new HashMap();
}
  • Main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
  • A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods. – They do not stand out in API documentation the way constructors do. so it can be difficult to figure out how to instantiate a class that providers static factory methods instead of constructors.

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.