effective java读书笔记

创建时间 2014-06-02 21:15:12 修改时间 2014-06-02 21:15:12

static factory method


One advantage of static factory methods is that, unlike constructors, they have names.

A second advantage of static factory methods is that, unlike constructors,
they are not required to create a new object each time they’re invoked.

A third advantage of static factory methods is that, unlike constructors,
they can return an object of any subtype of their return type.
thus,it can make a service provider framework.
A service provider framework is a system in which
multiple service providers implement a service, and the system makes the imple-
mentations available to its clients, decoupling them from the implementations.

A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.


The main disadvantage of providing only static factory methods is that
classes without public or protected constructors cannot be subclassed.

A second disadvantage of static factory methods is that they are not
readily distinguishable from other static methods.

Item 2: Consider a builder when faced with many constructor parameters

the telescoping constructor pattern works, but it is hard to write
client code when there are many parameters, and harder still to read it.

JavaBeans Pattern传参 优点

allows inconsistency, mandates mutability

JavaBeans Pattern传参 disadvantage

a JavaBean may be in an
inconsistent state partway through its construction.不合要求的对象,引起程序错误

the JavaBeans pattern precludes the possibility of making a class immutable 。线程安全

Builder pattern 描述



NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).

This client code is easy to write and, more importantly, to read. The Builder pat-
tern simulates named optional parameters as found in Ada and Python.

参数很多,而且可选的时候用 builder pattern 最合适

Item 3: Enforce the singleton property with a private constructor or an enum type


Item 4: Enforce noninstantiability with a private constructor

a class can be
made noninstantiable by including a private constructor

Item 5: Avoid creating unnecessary objects


prefer primitives to
boxed primitives, and watch out for unintentional autoboxing.

avoiding object creation by maintaining your own object pool is a
bad idea unless the objects in the pool are extremely heavyweight.

Item 6: Eliminate obsolete object references

Another common source of memory leaks is caches. A third common source of memory leaks is listeners and other callbacks

Item 7: Avoid finalizers

Finalizers are unpredictable, often dangerous, and generally unnecessary


  1. 安全记录,记录哪个对象没有安全卸载
  2. 本地对象的卸载,因为gc不知道本地对象