单例模式的Seven种写法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值