Singleton模式

这几天感觉想写点什么,但又没什么好写,最近又听人说起单例模式,所以想复习一下,把它写在这里。
单例就是指一个类只有一个实例。准确定义:

[color=darkblue][size=medium]The Single pattern provides the possibility to control the number of instances(mostly one) that are allowed to be made.We also receive a global
point of access to it(them).[/size][/color]

实现方法有三种:

1、采用synchronized方法的方式实现。


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


此方法有一些不足:因为只有第一次执行此方法时,才真正需要同步,一旦设置好uniqueInstance变量,就不再需要同步此方法。因此存在一些性能影响。

2、急切实例化


public class EagerSingleton {
private static EagerSingleton uniqueInstance = new EagerSingleton();
private EagerSingleton(){}
public static EagerSingleton getInstance(){
return uniqueInstance;
}
}


此方法在使用之前就把对象创建好了,所以不存在同步问题。如果在创建和运行时负担不太重的话,则较为合理。

3、双重检查加锁


public class DoubleCheckedSingleton {
private volatile static DoubleCheckedSingleton uniqueInstance;
private DoubleCheckedSingleton() {
}
public static DoubleCheckedSingleton getInstance() {
if (uniqueInstance == null) {
synchronized (DoubleCheckedSingleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new DoubleCheckedSingleton();
}
}
}
return uniqueInstance;
}
}


volatile: 当uniqueInstance被实例化时,多个线程正确地处理uniqueInstance变量,在JAVA 5 中有效。

单例模式的使用场合:
[color=darkblue]
[size=medium]When only one instance or a specific number of instances of a class are allowed.
Facade objects are often Singletons because only one Facade object is required.
[/size][/color]
就是说当一个对象只需要一个实例或明确的实例个数时才被使用。外观对象(具体可见外观模式)通常就是单例模式。

优点:
[size=medium][color=darkblue] * Controlled access to unique instance.
* Reduced name space.
* Allows refinement of operations and representations.[/color][/size]

缺点:
[size=medium][color=darkblue] Singleton pattern is also considered an anti-pattern by some people,who feel that it is overused,introducing unnecessary limitations in situations where a sole instance of a class is not actually required. [/color] [/size]

最新发现一种,就是通过枚举enum的方式:


public enum Elvis {
INSTANCE;
private int age;
public int getAge() {
return age;
}
}

and then called Elvis.INSTANCE.getAge()也可以这样:


public enum Elvis {
INSTANCE;
private int age;


public static int getAge() {
return INSTANCE.age;
}
}

and called Elvis.getAge()
优点:无偿的提供了序列化机制,能绝对保证实例的唯一性,是实现单例的最佳方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值