本文共 1100 字,大约阅读时间需要 3 分钟。
静态工厂方法的优势:
1它们有名称,表意更清楚。
2不必在每次调用它们的时候都创建一个新对象
3它们可以返回原返回类型的任何子类型的对象。
4在创建参数化类型实例的时候,它们是代码变得更加简单。
缺点:
1类如果不含有公有的或者受保护的构造器,就不能被子类化
2它们与其他的静态方法实际上没有任何区别,不方便辨认。
服务提供者框架简介:
服务提供者框架有三个重要的组件:服务接口,这是提供者实现的,供客户使用的,
提供者注册API,这是系统用来注册实现,让客户端访问他们的;服务访问API,是客户端用来获取服务的实例的。
例子:
public interface Service { //some method}
public interface Provider { Service newService();}
public class Services { private Services() { } private static final Mapproviders = new ConcurrentHashMap<>(); public static final String DEFAULT_PROVIDER_NAME=" "; public static void registerDefaultProvider(Provider p){ registerProvider(DEFAULT_PROVIDER_NAME,p); } public static void registerProvider(String name,Provider p){ providers.put(name,p); } public static Service newInstance(){ return newInstance(DEFAULT_PROVIDER_NAME); } public static Service newInstance(String name){ Provider p=providers.get(name); if(p==null) throw new IllegalArgumentException("No provider registered with name: "+name); return p.newService(); }}
转载地址:http://sljqi.baihongyu.com/