考虑使用静态工厂方法来替代构造方法, 这样的做的好处有四点. 1. 更好的表意 有的构造方法实际上有特殊的含义, 使用静态工厂方法能更好的表达出他的意思. 例如 BigInteger(int, int, Random) , 它返回一个可能是素数的 BigInteger. 使用工厂方法 BigInteger.probablePrime 可以更好的表达出他的意思 2. 无需每次创建新对象 在某些场景下, 我们无需每次都创建新的对象, 这样就可以使用静态工厂方法替代构造方法, 例如 Boolean.v…
获得一个类的实例的传统方法是公共的构造方法,还可以提供一个公共的静态工厂方法(一个返回值为该类实例的简单静态方法), 例如Boolean(boolean 的封装类) public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; } 此方法将boolean的原始值转变成Boolean对象的引用. 注意:这里的静态工厂方法与设计模式中的工厂方法不一样.静态工厂方法有优缺点. 优点:①与构造方法相…
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.…
获取类的实例的方法有很多种,在这很多种方法中,它们各有优缺,各有特点.这里,只介绍2中方法 1.使用构造方法 public class Person { private String sex; /** * <构造函数> */ public Person(String sex) { this.sex = sex; System.out.println("this is constructor method"); } } 调用如下: public static void mai…
Chapter 2 Creating and Destroying Objects item 1:Consider static factory methods instead of constructors 一个static factory method只不过是一个返回这个类的实例的static方法.与设计模式中的factory method是不同的概念.static factory methods有几点好处: 一.它们可以有自己的名字,而不像constructor只能与类名相同.一个好的名字…
本文参考 本篇文章参考自<Effective Java>第三版第一条"Consider static factory methods instead of constructors" 另外参考了其它几篇文章的解读: https://www.cnblogs.com/dyj-blog/p/8867028.html https://blog.csdn.net/u014129886/article/details/89670049 前言 第一条的篇章来自"Creating…
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st language I have chosen for this migration. It's a nice chance to read some great books like "Effective Java 2nd Edition" and share the note for what I…
<Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将近8年的时间,但随着Java 6,7,8,甚至9的发布,Java语言发生了深刻的变化. 读书笔记 第1章 介绍 (Introduction) 第2章 创建和销毁对象(Creating and Destroying Objects) 第1条 考虑用静态工厂方式替代构造器(Consider static factory m…
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating and Destroying Objects Consider static factory methods instead of constructors Consider a builder when faced with many constructor parameters Enforce the s…
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Objects Consider static factory methods instead of constructors (factory方法可以拥有名称,可以避免重复创建,比如单例模式) Consider a builder when faced with many constructor parameter…