首页 > 代码库 > Read Notes:[Effective Java] Consider static factory methods instead of Constructors

Read Notes:[Effective Java] Consider static factory methods instead of Constructors

Providing a static method instead of a public constructor has both advantages and disadvantages.

  • One advantage of static factory methods is that, unlike constructors,they have names.

  •  A Second advantage of static factory methods is that, unlike constructors, they are not require to create a new object each time they are invoked.

  • A Third advantage of static factory methods is that, unlike constructors, they can return an object of any sub-type of their return type.

  • A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.

// Service provider framework sketch
// Service interface
public interface Service {
    ...// Service-specific methods go here
}
// Service provider interface
public interface Provider {
    Service newService();
}
// Noninstantiable class for service registration and access
public class Services {
    private Services() {} // Prevents instantion
    // Maps service names to services
    private static final Map<String, Provider> providers =
            new ConcurrentHashMap<String, Provider>();
    public static final String DEFAULT_PROVIDER_NAME = "<def>";
    // Provider Registration API
    public static void registerDefaultProvider(Provider, p) {
        registerProvider(DEFAULT_PROVIDER_NAME, p);
    }
    public static void registerProvider(String name, Provider p) {
        providers.put()
    }
    // Service access API
    public Service newInstance() {
        return newInstance(DEFAULT_PROVIDER_NAME);
    }
    public Service newInstance(String name) {
        Provider p = providers.get(name);
        if (p == null) {
            throw new IllegalArgumentException("No provider register with name:" + name);
        }
        return p.newService();
    }
}
  • The main disadvantage of providing only static factory methods is that classes without public or protected constructors can not be sub-classed.

  • A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.