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

时间:2014-07-30 17:54:24   收藏:0   阅读:344

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

// 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();
    }
}


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

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!