//1.懒汉模式 线程不安全
public class Singleton
{
static Singleton singleton;
private Singleton()
{}
public static Singleton GetInstance()
{
if( singleton==null )
{
singleton = new Singleton(); //实例化对象
}
return singleton;
}
}
///////////////////////////////////////////////////////////////////////////
//懒汉模式 线程安全(加锁操作)
static Singleton singleton;
public static synchronized Singleton GetInstance()
{
if( singleton==null )
{
singleton = new Singleton();
}
return singleton;
}
///////////////////////////////////////////////////////////////////////////
//3. 饿汉模式 非变种
static Singleton sigleton = new Singleton(); //饿汉就是直接构造
//构造方法私有化
public static Singleton GetInstance()
{
return singleton;
}
/////////////////////////////////////////////////////////////////////////
//4.饿汉模式 变种 —->最饿的模式,在静态快里new对象
static Singleton singleton = null;
//构造方法私有
static{
singleton = new Singleton(); //程序开始先执行静态块,就是先构造对象
}
public static Singleton GetInstance()
{
return singleton;
}
///////////////////////////////////////////////////////////////////////
//5.静态内部类
private static class SingHand{
//内部类构造方法私有化
private static final Singleton singleton = new Singleton; //!!!!!!!!!!!!!
}
public static Singleton GetInstance
{
return SingHand.singleton;
}
///////////////////////////////////////////////////////////
//枚举法
///////////////////////////////////////////////////////////////////////
//双重校验锁 –>2的升级版
static Singleton singleton=null;
public static Singleton GetInstance()
{
if( singleton == null )
{
synchronized( Singleton.class );
if( singleton == null )
{
singleton = new Singleton();
}
}
}
本文详细介绍了单例模式的五种实现方式:懒汉模式(线程安全与不安全)、饿汉模式(标准与变种)、静态内部类及枚举法,并对比了它们的特点。
951

被折叠的 条评论
为什么被折叠?



