Effective Java 学习笔记第1条 --- 考虑用静态工厂方法代替构造函数
静态工厂方法好处:
静态工厂方法坏处:
总结:
???? 静态工厂方法和公有的构造函数都有他们各自的用途,我们要理解他们各自的长处,避免一上来就用构造函数,通常静态工厂更加合适。如果没有其他因素强烈的影响我们的选择,最好还是简单的选择构造函数,毕竟他是语言提供的规范。
// Provider framework sketchpublic abstract class Foo {// Maps String key to corresponding Class objectprivate static Map implementations = null;// Initializes implementations map the first time it's calledprivate static synchronized void initMapIfNecessary() {if (implementations == null) {implementations = new HashMap();// Load implementation class names and keys from// Properties file, translate names into Class// objects using Class.forName and store mappings....}}public static Foo getInstance(String key) {initMapIfNecessary();Class c = (Class) implementations.get(key);if (c == null)return new DefaultFoo();try {return (Foo) c.newInstance();} catch (Exception e) {return new DefaultFoo();}}}