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

深入探讨Singleton模式的实现方式
本文详细介绍了如何使用静态最终字段和私有构造函数来实现Singleton模式,并提供了使用枚举类型作为替代的方法。同时,文章还讨论了如何在序列化场景下保持Singleton属性不变,以及如何防御反射攻击。

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() { ... }

}

   

转载于:https://www.cnblogs.com/haokaibo/p/enforce-the-singleton-property-with-a-private-constructor-or-an-enum-type.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值