用 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 容器可以为普通的类创建单例,它是怎么做到的呢?


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM