码迷,mamicode.com
首页 > 编程语言 > 详细

Effective Java 英文 第二版 读书笔记 Item 3:Enforce the singleton property with a private constructor or an enum type.

时间:2015-09-04 07:14:41      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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

Effective Java 英文 第二版 读书笔记 Item 3:Enforce the singleton property with a private constructor or an enum type.

标签:

原文地址:http://www.cnblogs.com/linkarl/p/4780957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!