effective java读书笔记

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

static factory method

advantage

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.

disadvantage

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 描述

采用内部类,建造immutable参数对象。

example:

NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).sodium(35).carbohydrate(27).build();

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

单例的确保,建议采用enum,防止serializable问题

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

废弃的对象变量要赋值null
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

finalize可以用在哪里?

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

记得调用super.finalize,不像构造方法,会自动调用上级构造方法;