zoukankan      html  css  js  c++  java
  • Effective Java 英文 第二版 读书笔记 Item 3:Enforce the singleton property with a private constructor or an enum type.

    Making a class a singleton can make it difficult to test clients.

    package singletonProperty;
    
    //ingleton with public final field 
    public class ElvisField {
        public static final ElvisField INSTANCE=new ElvisField();
        private ElvisField(){
            
        }
        
    }
    package singletonProperty;
    
    //Singleton with static factory 
    public class ElvisMethod {
        
        private static final ElvisMethod INSTANCE=new ElvisMethod();
        
        private ElvisMethod(){
            
        }
        
        public static ElvisMethod getInstance() {
            return INSTANCE;
        }
        
    }
    package singletonProperty;
    
    //Enum singleton - the preferred approach
    public enum ElvisEnum {
        INSTANCE;
    }

    A single-element enum type is the best way to implement a singleton

  • 相关阅读:
    getJson
    mongodb在java中的查询
    Fragment
    android权限
    json输出
    Android Service
    javascript
    android
    Myeclipse启动报错: Invalid 'log4jConfigLocation' parameter
    Android-Activity生命周期
  • 原文地址:https://www.cnblogs.com/linkarl/p/4780957.html
Copyright © 2011-2022 走看看