懒汉模式
public class SingleDemo {
private static SingleDemo demo;
private SingleDemo(){}
public static synchronized SingleDemo getDemo(){
if (demo!=null){
return demo;
}else {
demo=new SingleDemo();
return demo;
}
}
}
public class Singleton
{
// 私有的、静态的成员保存唯一的实例
private static Singleton inst;
// 私有构造器,避免被别人创建实例
private Singleton(){}
// 提供一个公共的、静态的方法,获取唯一的实例
public static Singleton getInstance()
{
// 很多示例代码都是在方法上加同步,但是基于“最小范围原则”,应该要用同步代码块
// 这样可以尽可能提升程序的并发性能
synchronized( Singleton.class )
{
// 判断inst是否为null,如果是null则新建一个
if( inst == null )
{
inst = new Singleton();
}
}
return inst;
}
}
饿汉模式
public class Singleton
{
// 私有的、静态的成员保存唯一的实例
// 在类被第一次使用的时候,就已经完成了加载。类的加载过程,系统保证线程安全。
private static Singleton inst = new Singleton();
// 私有构造器,避免被别人创建实例
private Singleton(){}
// 提供一个公共的、静态的方法,获取唯一的实例
public static Singleton getInstance()
{
return inst;
}
}