Java代码实现单例模式

public class Single {
/*private static final Single single=new Single();
private Single(){}
public static Single getInstance(){
return single;
}*/
private static Single single=null;
private Single(){}
public static Single getInstance(){
if(single==null){
single=new Single();
}
return single;
}
}

在静态代码块里实现浪费时间节省空间,而通过为属性赋值节省时间浪费空间,类加载的时候会先执行静态代码块,所以采用第一种方法更好。

关键是把构造方法声明为私有的从而只能在类中创建对象而不能在类外部创建对象。

原文地址:https://www.cnblogs.com/blythe/p/7365017.html