单例模式的Seven种写法

来源:互联网 发布:science online数据库 编辑:程序博客网 时间:2024/06/16 06:05

//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();
}
}
}

原创粉丝点击