面对更新迅速的互联网技术,非科班出身的孩子更要努力学习。最近在学习android的同时也同步学习数据结构与算法(我的简书http://www.jianshu.com/u/62f2144f08e0,欢迎观看)与Effective Java。尤其是Effective Java,看了顿时觉得书上说的好有道理,感觉进入了一个新的学习领域。
静态工厂方法相对于构造器的优势:
1、静态工厂方法有名称。
构造器的名称是固定的,当有多个构造器时,调用容易搞混。静态工厂方法是名称是任意的,可以为它起一个代表其用途的名称,方便调用。
//两种不同类型线程池
/**
* Creates a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available, and uses the provided
* ThreadFactory to create new threads when needed.
* @param threadFactory the factory to use when creating new threads
* @return the newly created thread pool
* @throws NullPointerException if threadFactory is null
*/
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
2、静态工厂方法不必在每次调用的时候创建一个新的对象
创建一个私有的构造器,并通过静态工厂通过单例模式进行调用可以保证对象的重用,避免不必要的对象创建。
Boolean a=Boolean.valueOf(false); //静态工厂方法不创建对象,只复用
Boolean b=new Boolean(false);
3、静态工厂方法可以返回类型的任何子类型的对象
主要适用于面向接口编程,根据输入参数的不同,输出不同类的实例,这样既可以提高灵活性,也降低了对象间的耦合度。
4、静态工厂方法创建参数化类型实例时,代码更简洁
Map<String,List<String>> m=new HashMap<String, List<String>>();
Map<String,List<String>> m=HashMap.newInstance();
public static <k,v> HashMap<k,v> newInstance(){
return new HashMap<k,v>();
}
静态工厂方法相对于构造器的劣势:
1、类如果没有共有的或受保护的构造器,就不能被子类化。此时就只能复合不能继承了。