单例模式(Singleton pattern)四种实现

[align=center][size=x-large]PART 1 快速预览[/size][/align]
[list]
[*][b]单例实现1:经典单例模式(Classic singleton pattern)[/b]
[/list]
[list=1]
[*]实现延迟实例化(Lazy instantiaze);线程不安全(thread-unsafe)
[*]可用来学习单例模式思想,但是因为线程不安全,所以[color=red]不建议使用[/color]。
[/list]

/**
* Classic singleton pattern
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/
public class Singleton {
// private static variable
private static Singleton singleton;

// private constructor
private Singleton() {
// do something useful such as initialized data
}

// provides a global point of access to it
public static Singleton getInstance() {
if ( singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}


[list]
[*][b]单例实现2:对方法同步加锁式单例(Synchronized method singleton pattern)[/b]
[/list]
[list=1]
[*]实现延迟实例化(Lazy instantiaze);线程安全(thread safe);每次访问都要等候别的线程离开该方法,性能低。
[*]解决了经典单例模式线程不安全的问题,但是性能低下,所以[color=red]不建议使用[/color]。
[/list]

/**
* Synchronized method singleton pattern
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/
public class Singleton {

private static Singleton singleton;

private Singleton() {}

public static synchronized Singleton getInstance() {
if ( singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}


[list]
[*][b]单例实现3:无延迟实例化式单例(Eagerly instantiaze singleton pattern)[/b]
[/list]
[list=1]
[*]非延迟实例化(eagerly instantiaze);线程安全(thread safe);
[*]在类加载的第一时间被初始化,[color=red]大部分场景都可胜任[/color]。丢失了延迟实例化特性,这带来的遗憾是还未被调用就已经实例化了。
[/list]

/**
* Eagerly singleton pattern
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/
public class Singleton {

private static Singleton singleton = new Singleton();

private Singleton() {}

public static synchronized Singleton getInstance() {
return singleton;
}
}


[list]
[*][b]单例实现4:双重检测加锁式单例(Double-checked locking singleton pattern)[/b]
[/list]
[list=1]
[*]实现延迟实例化(Lazy instantiaze);线程安全(thread safe);
[*]在[color=red]最佳的单例实现[/color],稍微复杂。
[/list]

/**
* Double checked singleton pattern
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/
public class Singleton {

private volatile static Singleton singleton = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
if ( singleton == null) {
synchronized (Singleton. class) {
if ( singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}


[align=center][size=x-large]PART 2 细细品鉴[/size][/align]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值