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/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    JS 获取当前时间,格式为年月日时分秒
    HTML Input=“file”文件上传,限制文件类型 Accept Attribute File Type (CSV)
    react使用redux操作购物车数据
    koa2实现对mysql的增删改查函数封装
    axios中get请求与post请求的简单函数封装
    canvas 简介
    H5 新API 续
    h5 新API
    JQuery
    DOM 文档对象模型
  • 原文地址:https://www.cnblogs.com/haokaibo/p/enforce-the-singleton-property-with-a-private-constructor-or-an-enum-type.html
Copyright © 2011-2022 走看看