用 Java 写一个单例类?

饿汉式单例

public class Singleton {

private Singleton(){}

private static Singleton instance = new Singleton();

public static Singleton getInstance(){

return instance;

}

}

 

懒汉式单例

public class Singleton {

private static Singleton instance = null;

private Singleton() {}

public static synchronized Singleton getInstance(){

if (instance == null) instance = new Singleton();

return instance;

}

}

注意:实现一个单例有两点注意事项,①将构造器私有,不允许外界通过构造器

创建对象;②通过公开的静态方法向外界返回类的唯一实例。这里有一个问题可

以思考:Spring 的 IoC 容器可以为普通的类创建单例,它是怎么做到的呢?

posted @   咔啡  阅读(1649)  评论(0)    收藏  举报
点击右上角即可分享
微信分享提示