-
单件模式
2020-10-17 15:49:39title: 设计模式–单件模式 date: 2020-10-04 author: tongji4m3 top: false cover: false coverImg: /images/1.jpg toc: true mathjax: false summary: 学习《Head Frist 设计模式》所做的笔记,主要介绍了单件模式...
title: 设计模式–单件模式
date: 2020-10-04
author: tongji4m3
top: false
cover: false
coverImg: /images/1.jpg
toc: true
mathjax: false
summary: 学习《Head Frist 设计模式》所做的笔记,主要介绍了单件模式的原则,类图,代码实现。
categories: 设计模式笔记
tags:- 设计模式
- Java
- UML
单件模式
作用
- 可用于线程池,缓存,日志对象等只能有一个实例的地方
- 单件模式可以确保只有一个实例被创建
- 利用单件模式,我们可以确保只有在需要的时候才会创建对象
定义
单件模式确保一个类只有一个实例,并提供一个全局访问点
实现
第一版
- 实现了延迟初始化
- 多线程不安全
public class Singleton { private static Singleton uniqueInstance; private Singleton() { } public static Singleton getInstance() { if(uniqueInstance==null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
第二版
- 保证了线程安全
- 效率低下,只有第一次执行此方法才需要同步。一旦设置好了
uniqueInstance
变量,就不需要同步该方法了,synchronized
就变成了累赘
public class Singleton { private static Singleton uniqueInstance; private Singleton() { } public static synchronized Singleton getInstance() { if(uniqueInstance==null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
第三版
-
饿汉式
-
JVM
在加载这个类时马上创建此唯一的单价实例
public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return uniqueInstance; } }
第四版
- 双重检查加锁
- 在
getInstance()
中减少使用同步,只有第一次会同步
public class Singleton { //保证线程的可见性 private volatile static Singleton uniqueInstance; private Singleton() { } public static Singleton getInstance() { if(uniqueInstance==null) { //估计只有几个线程会进到这里 synchronized (Singleton.class) { //这些线程逐个进来,但是只有第一个线程会进入到下面的if //其他的线程进来时,已经初始化完毕了,就不好初始化多个实例 if(uniqueInstance==null) { //第一个线程进来,初始化 uniqueInstance = new Singleton(); } } } return uniqueInstance; } }
收藏数
3,333
精华内容
1,333