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/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Erlang学习笔记2
    erlang的Socket参数含义
    Erlang 日期和时间处理、时间戳转换
    图(有向)-拓扑排序
    图(无向连通无权图)-广度优先搜索
    图(无向连通无权图)-深度优先搜索
    图(无向连通无权值图)深度优先生成最小生成树
    客户关系管理系统
    字符串类
    I/O流
  • 原文地址:https://www.cnblogs.com/haokaibo/p/enforce-the-singleton-property-with-a-private-constructor-or-an-enum-type.html
Copyright © 2011-2022 走看看