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. 使用WinDbg调试SQL Server——入门

    这篇文章我想探究下SQL Server里完全不同的领域:如果使用WinDbg(来自针对Windows的调试工具)调试SQL Server.在我们进入枯涩细节之前,我想详细解释下为什么选择这样晦涩的话题 ...

  2. ASP.NET WebForm与MVC优缺点

    发表于我的个人网站中,请点击阅读!

  3. C#中引用类型和值类型

    C#的值类型包括:结构体(数值类型,bool型,用户定义的结构体),枚举,可空类型. C#的引用类型包括:数组,用户定义的类.接口.委托,object,字符串. 值类型和引用类型的区别在于,值类型的变 ...

  4. mysql 随机字符的产生方法

    需求:需要插入随机数据,长度为6位,包含数字和大写字母. 一般来说我们会写类似如下的存储过程片断: ) default 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM ...

  5. awk引用外部变量及调用系统命令方法

    目标:想用awk与scp命令批量传送文件 前提:先搭好主机间的免密登陆环境(参考:http://www.cnblogs.com/tankaixiong/p/4172942.html) 实现脚本方法: ...

  6. [Tool] 常用开发工具注册码(持续更新)

    OS win10 激活 命令行 打开命令提示符( 管理员 ) 输入 slmgr /ipk W269N-WFGWX-YVC9B-4J6C9-T83GX 回车 再输入 slmgr /skms kms.xs ...

  7. mysql中如何把字符串转换成日期类型

    select date_format('2013-03-09','%Y-%m-%d'); select date_format('2013-03-09','%y-%m-%d'); select STR ...

  8. 环信SDK与Apple Watch的结合(2)

    这一篇主要是介绍怎么拖apple watch上的相关页面,附源码EMWatchOCDemo. 需要在工程中的“EMWatchOCDemo WatchKit App”中进行操作,该文件夹的结构如图 Wa ...

  9. [迷宫中的算法实践]迷宫生成算法——递归分割算法

    Recursive division method        Mazes can be created with recursive division, an algorithm which wo ...

  10. jquery 回到 顶部

    1. 页面内容较多, 从底部超链接 点击回到页面顶部 // 回到顶部 var $top = $('<a class="doc-gotop" href="javasc ...