首页 > 其他 > 详细

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

时间:2014-02-26 13:57:13      阅读:292      评论:0      收藏: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() { ... }

}

  

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

原文:http://www.cnblogs.com/haokaibo/p/3567784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!