引言
网上有很多介绍设计模式系列的优秀文章,看懂不一定是真懂,能写出来,说出个1、2、3点才算是真的懂了,如果能灵活的应用到工作中才算是真的熟练。
1、模式场景
定义系统中一个唯一的ID生成器。
2、模式结构
Singleton:单例 定义一个类只有一个实例,该实例向整个系统提供服务。
3、示例代码
3.1、单例
public class IDSingleton {
private AtomicLong atomicLong = new AtomicLong(0);
private static volatile IDSingleton idSingleton;
public static IDSingleton getIdSingleton(){
if(idSingleton == null) {
synchronized (IDSingleton.class) {
if (idSingleton == null) {
idSingleton = new IDSingleton();
}
}
}
return idSingleton;
}
//获取自增id
public long getAutoId(){
return idSingleton.atomicLong.incrementAndGet();
}
}
3.2、测试类
public class IDSingletonTest {
public static void main(String[] args) throws InterruptedException {
//这里使用线程安全的Set
Set<Long> set = Collections.newSetFromMap(new ConcurrentHashMap());
CountDownLatch countDownLatch = new CountDownLatch(10000);
//开启10000个线程测试并发
for(int i = 0; i < 10000; i++){
new Thread() {
@Override
public void run() {
long autoId = IDSingleton.getIdSingleton().getAutoId();
set.add(autoId);
countDownLatch.countDown();
}
}.start();
}
countDownLatch.await();
System.out.println(set.size());
}
}
4、模式优点
- 提供了对唯一实例的受控访问。
- 节约了系统的资源,无需频繁的创建和销毁对象。
5、模式缺点
- 没有抽象层,扩展难。
- 单例类职责过重,在一定程度上违反了“单一职责原则”。
结束语
单例模式有很多应用场景,例如windows的资源管理器、回收站都是单例的应用,下一篇:模式——适配器模式。