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

posted @ 2015-09-03 23:18  郁闷紫番薯  阅读(229)  评论(0编辑  收藏  举报