zoukankan      html  css  js  c++  java
  • Effective Java 03 Enforce the singleton property with a private constructor or an enum type

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

    }

       

    作者:小郝
    出处:http://www.cnblogs.com/haokaibo/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Linux/UNIX线程(1)
    jeecms 链接标签
    JEECMS 系统权限设计
    jeecms 前台拦截器的研究与改造
    jeecms系统_自定义对象流程
    jeecms技术预研
    jeecms获取绝对路径
    JEECMS自定义标签
    jeecms项目相关配置文件
    [jeecms]获取父栏目下的子栏目名称
  • 原文地址:https://www.cnblogs.com/haokaibo/p/enforce-the-singleton-property-with-a-private-constructor-or-an-enum-type.html
Copyright © 2011-2022 走看看