代码改变世界

Effective Java 03 Enforce the singleton property with a private constructor or an enum type

2014-02-25 21:57  小郝(Kaibo Hao)  阅读(393)  评论(0编辑  收藏  举报

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 INSTANCE = new Elvis();

private Elvis() { ... }

public static Elvis getInstance(){ return INSTANCE; }

public void leaveTheBuilding() { ... }

}

   

NOTE

caveat: a privileged client can invoke the private constructor reflectively (Item 53) with the aid of the AccessibleObject.setAccessible method. If you need to defend against this attack, modify the constructor to make it throw an

exception if it's asked to create a second instance.

   

To handle the serializable object to be new object to the singleton object please implement the method below:

// readResolve method to preserve singleton property

private Object readResolve() {

// Return the one true Elvis and let the garbage collector

// take care of the Elvis impersonator.

return INSTANCE;

}

   

If you use java release 1.5 or above you can just use enum type.

// Enum singleton - the preferred approach

public enum Elvis {

INSTANCE;

public void leaveTheBuilding() { ... }

}