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.
the telescoping constructor pattern works, but it is hard to write
client code when there are many parameters, and harder still to read it.
考虑有多个参数的构造函数,创建了一堆不同数量参数的构造方法。
allows inconsistency, mandates mutability
a JavaBean may be in an
inconsistent state partway through its construction.不合要求的对象,引起程序错误
the JavaBeans pattern precludes the possibility of making a class immutable 。线程安全
采用内部类,建造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 最合适
单例的确保,建议采用enum,防止serializable问题
a class can be
made noninstantiable by including a private constructor
尽量重用对象。
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.
废弃的对象变量要赋值null
Another common source of memory leaks is caches. A third common source of memory leaks is listeners and other callbacks
Finalizers are unpredictable, often dangerous, and generally unnecessary
finalize可以用在哪里?
记得调用super.finalize,不像构造方法,会自动调用上级构造方法;