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/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Spring总结
    Json
    智能搜索
    Ajax
    include指令和include标签的区别
    jsp状态管理
    Model1
    JavaBean
    JSP内置对象的解析
    镜像地址管理工具nrm
  • 原文地址:https://www.cnblogs.com/haokaibo/p/enforce-the-singleton-property-with-a-private-constructor-or-an-enum-type.html
Copyright © 2011-2022 走看看