effective-java阅读笔记2

effective-java阅读笔记2
Enforce the singleton property with a private constructor(用私有构造函数执行单例singlton)

A singleton is simply a class that is instantiated exactly once [Gamma98, p. 127].如数据库资源等.
There are two approaches to implementing singletons. Both are based on keeping the
constructor private and providing a public static member to allow clients access to the sole
instance of the class. In one approach, the public static member is a final field:
// Singleton with final field
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis() {
...
}
... // Remainder omitted
}

1:构造函数私有
2:提供一个静态static的final成员

The private constructor is called only once, to initialize the public static final field
Elvis.INSTANCE. 
Exactly one Elvis instance will exist once the Elvis class is initialized—no more,
no less. Nothing that a client does can change this.

In a second approach, a public static factory method is provided instead of the public static final field:
// Singleton with static factory
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis() {
...
}
public static Elvis getInstance() {
return INSTANCE;
}
... // Remainder omitted
}

用静态方法返回,而不是直接返回一个实例.

如果对对象序列化,要做多一点工作.如
To make a singleton class serializable (Chapter 10), it is not sufficient merely to add
implements Serializable to its declaration. To maintain the singleton guarantee, you must
also provide a readResolve method (Item 57). Otherwise, each deserialization of a serialized instance will result in the creation of a new instance, 否则,经过对象反序列化后,会导致创建了一个新的对象.leading, in the case of our example, to spurious Elvis sightings. To prevent this, add the following readResolve method to the Elvis class:
// readResolve method to preserve singleton property
private Object readResolve() throws ObjectStreamException {
/*
* Return the one true Elvis and let the garbage collector
* take care of the Elvis impersonator.
*/
return INSTANCE;
}

你可能感兴趣的:(effective-java阅读笔记2)