Principle When implement the singleton pattern please decorate the INSTANCE field with "static final" and decorate the constructor with "private". // Singleton with static factory public class Elvis { private static final Elvis INSTANC…
Item3:Enforce the singleton property with a private constructor or an enum type 采用枚举类型(ENUM)实现单例模式. public enum Elvis { INSTANCE; public void leaveTheBuiding(){ System.out.println("a single-element enum type is the best way to implement a singleton&q…
 1. 通过一个公开的字段来获取单例 // Singleton with public final field public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } public void leaveTheBuilding() { ... } } The main advantage of the public field approach is that th…
Item4:Enforce noninstantiability with a private constructor 通过构造私有化,禁止对象被实例化. public class UtilClass { private UtilClass(){ //防止类内的函数调用构造函数创建对象 throw new AssertionError(); } }…
A class can be made noninstantiable by including a private constructor. // Noninstantiable utility class public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } ... //…
Advantage It simulates named optional parameters which is easily used to client API. Detect the invariant failure(validation error of field) as soon as the invalid parameters are passed, instead of waiting for build to be invoked. The builder can fil…
Item2:Consider a builder when faced with many constructor parameters 当构造方法有多个参数时,可以考虑使用builder方式进行处理. 实例代码: public class NutritionFacts { private final int servingSize; private final int servings; private final int calories; private final int fat; pr…
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>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. 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…