Advantage

  • Unlike constructors, they have names. (BigInteger.probablePrime vs BigInteger(int, int, Random)
  • They are not required to create a new object each time they're invoked(Flyweight pattern). This ensures that a.equals(b) if and only if a = = b. Then the client can use = = instead of equals method which gets better performance to Equals method.
  • It can return an object of any subtype of their return type.(This gives you great flexibility in choosing the class of the returned object. )

    /********************sample code ******************/

    // 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 instantiation (Item 4)

    // 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(name, p);

    }

    // Service access API

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

    }

    }

  • Reduce the verbosity of creating parameterized type instances.
Disadvantages
  • The class without public or protected constructors cannot be subclassed.
  • They are not readily distinguishable from other static methods.

Here are some common names for static factory methods:

• valueOf—Returns an instance that has, loosely speaking, the same value as its

parameters. Such static factories are effectively type-conversion methods.

• of—A concise alternative to valueOf, popularized by EnumSet(Item 32).

• getInstance—Returns an instance that is described by the parameters but

cannot be said to have the same value. In the case of a singleton, getInstance

takes no parameters and returns the sole instance.

• newInstance—LikegetInstance, except that newInstanceguarantees that

each instance returned is distinct from all others.

• getType—Like getInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

• newType—Like newInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

Effective Java 01 Consider static factory methods instead of constructors的更多相关文章

  1. Effective Java - Item 1: Consider static factory methods instead of constructors

    考虑使用静态工厂方法来替代构造方法, 这样的做的好处有四点. 1. 更好的表意 有的构造方法实际上有特殊的含义, 使用静态工厂方法能更好的表达出他的意思. 例如 BigInteger(int, int ...

  2. 读Effective Java笔记之one:static Factory methods instead of Constructors (静态工厂方与构造器)

    获取类的实例的方法有很多种,在这很多种方法中,它们各有优缺,各有特点.这里,只介绍2中方法 1.使用构造方法 public class Person { private String sex; /** ...

  3. Effective Java P2 Item1 Consider static factory methods instead of constructors

    获得一个类的实例的传统方法是公共的构造方法,还可以提供一个公共的静态工厂方法(一个返回值为该类实例的简单静态方法), 例如Boolean(boolean 的封装类) public static Boo ...

  4. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  5. Effective Java 第三版笔记(目录)

    <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将近8年的时 ...

  6. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  7. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  8. Effective Java —— 用静态工厂方法代替构造器

    本文参考 本篇文章参考自<Effective Java>第三版第一条"Consider static factory methods instead of constructor ...

  9. 《Effective Java》读书笔记 - 2.创建和销毁对象

    Chapter 2 Creating and Destroying Objects item 1:Consider static factory methods instead of construc ...

随机推荐

  1. 请求参数到表述层的类型转换——Struts2

    一.简介 说明:HTTP 协议传输数据没有类型的概念,在服务器端是通过 request.getParameter().request.getParameterValue() 方法得到请求参数为 Str ...

  2. 【WinRT】国内外 Windows 应用商店应用开发者博客收集

    本文格式:博主名 博客链接 本人点评.排名不分先后. 中文: 博客园: webabcd http://www.cnblogs.com/webabcd/ 微软最有价值专家(MVP),他做的 Win8.1 ...

  3. 二维KMP - 求字符矩阵的最小覆盖矩阵 - poj 2185

    Milking Grid Problem's Link:http://poj.org/problem?id=2185 Mean: 给你一个n*m的字符矩阵,让你求这个字符矩阵的最小覆盖矩阵,输出这个最 ...

  4. C#设计模式——模板方法(Template Method)

    一.概述在软件开发中,对某一项操作往往有固定的算法结构,而具体的子步骤会因为不同的需要而有所不同.如何可以在稳定算法结构的同时来灵活应对子步骤变化的需求呢?二.模板方法模板方法是一种常见的设计模式,它 ...

  5. MVC视图展现模式之移动布局

    参考:http://www.cnblogs.com/dunitian/p/5218140.html 简单点,直接上用法 新建MVC项目,在golbal.asax中添加如下代码 //添加一个自定义后缀 ...

  6. 将HTML5 Canvas的内容保存为图片

    主要思想是借助Canvas自己的API - toDataURL()来实现,整个实现 HTML + JavaScript的代码很简单. 代码如下: <html> <meta http- ...

  7. Python打包-py2exe使用

    Py2exe 64位下载地址:http://download.csdn.net/detail/henujyj/8532827 Py2exe 32位下载地址:https://sourceforge.ne ...

  8. 重新想象 Windows 8 Store Apps (57) - 本地化和全球化

    [源码下载] 重新想象 Windows 8 Store Apps (57) - 本地化和全球化 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 本地化和全球化 本地化 ...

  9. [moka同学笔记]Yii2.0 dropDownList的使用(二)

    方法一: <?php $psObjs = Poststatus::find()->all(); $allStatus = ArrayHelper::map($psObjs,'id','na ...

  10. Servlet获得Http请求,GET/POST

    Servlet获得Http请求 Http请求信息格式 请求行(方法提交方式,URI,Http协议版本) GET方式提交:URI会包含查询字符串 POST方式提交:URI不会包含查询字符串 请求头 Ho ...