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…
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…
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…
本文参考 本篇文章参考自<Effective Java>第三版第二条"Consider a builder when faced with many constructor parameters" 静态工厂方法和构造器的不足之处 当一个类中有大量的字段时,尽管能通过设置不同的形参列表和方法名进行重载或使用静态工厂方法进行一定的简化,但我们还是会难以避免地为方法签名设置了较长的形参列表并直接使用到这些方法,以致于"it is hard to write client…
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只能与类名相同.一个好的名字…
第1章 引言 第2章 创建和销毁对象 第1条:考虑用静态工厂方法代替构造器(Consider static factory methods instead of constructors) 第2条:遇到多个构造器参数时要考虑用构建器(Consider a builder when faced with many constructor parameters ) 第3条:用私有构造器或者枚举类型强化Singleton属性( Enforce the singleton property with a…