获得一个类的实例的传统方法是公共的构造方法,还可以提供一个公共的静态工厂方法(一个返回值为该类实例的简单静态方法), 例如Boolean(boolean 的封装类) public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; } 此方法将boolean的原始值转变成Boolean对象的引用. 注意:这里的静态工厂方法与设计模式中的工厂方法不一样.静态工厂方法有优缺点. 优点:①与构造方法相…
考虑使用静态工厂方法来替代构造方法, 这样的做的好处有四点. 1. 更好的表意 有的构造方法实际上有特殊的含义, 使用静态工厂方法能更好的表达出他的意思. 例如 BigInteger(int, int, Random) , 它返回一个可能是素数的 BigInteger. 使用工厂方法 BigInteger.probablePrime 可以更好的表达出他的意思 2. 无需每次创建新对象 在某些场景下, 我们无需每次都创建新的对象, 这样就可以使用静态工厂方法替代构造方法, 例如 Boolean.v…
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…
传统的方式获取一个类的实例,是通过提供一个 public 构造器.这里有技巧,每一个程序员应该记住.一个类可以对外提供一个 public 的 静态工厂方法 ,该方法只是一个朴素的静态方法,不需要有太多复杂的逻辑,只需要返回该类的实例. 这里通过 Boolean (是原始类型 boolean 的包装类)举一个简单的例子: public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; } 这个方…
This chapter concerns creating and destorying objects : when and how to create them, when and how to avoid creating them, how to ensure they are destoryed in a timely manner, how to manage any cleanup actions that must precede their destruction.…
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…