码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-07-30 17:54:24      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:item 1   effective java   static factory methods   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.


Read Notes:[Effective Java] Consider static factory methods instead of Constructors,布布扣,bubuko.com

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

标签:item 1   effective java   static factory methods   constructors   

原文地址:http://kinken.blog.51cto.com/4569049/1532801

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!