【设计模式-01】Singleton单利模式

2024-01-08 21:04

本文主要是介绍【设计模式-01】Singleton单利模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、方式1(最常用,推荐使用)

单例实现方式一: 饿汉式

类加载到内存后,就实例化一个单例,JVM保证线程安全

简单实用,推荐使用。

唯一缺点: 不管用到与否,类装载时就完成加载。

/*** @description: 单例实现方式一: 饿汉式 <br>*     类加载到内存后,就实例化一个单例,JVM保证线程安全 <br>*     简单实用,推荐使用。<br>*     唯一缺点: 不管用到与否,类装载时就完成加载。* @author: flygo* @time: 2022/5/27 22:17*/
public class SingletonManager01 {private static final SingletonManager01 INSTANCE = new SingletonManager01();private SingletonManager01() {}public static SingletonManager01 getInstance() {return INSTANCE;}public static void main(String[] args) {SingletonManager01 singletonManager01 = SingletonManager01.getInstance();SingletonManager01 singletonManager011 = SingletonManager01.getInstance();System.out.println(singletonManager01 == singletonManager011);}
}

二、方式2

静态语句块,和方式一一样

/*** @description: 同第一种方式一样,静态语句块实现* @author: flygo* @time: 2022/5/27 22:24*/
public class SingletonManager02 {private static final SingletonManager02 INSTANCE;private SingletonManager02() {}static {INSTANCE = new SingletonManager02();}public static SingletonManager02 getInstance() {return INSTANCE;}public static void main(String[] args) {SingletonManager02 singletonManager02 = SingletonManager02.getInstance();SingletonManager02 singletonManager021 = SingletonManager02.getInstance();System.out.println(singletonManager02 == singletonManager021);}
}

三、方式3(多线程有问题)

懒汉式,虽然达到了按需初始化的目的,但带来了线程不安全的问题

/*** @description: lazy loading 懒汉式加载,虽然达到了按需加载的目的,但带来了线程不安全的问题* @author: flygo* @time: 2022/7/4 09:32*/
public class SingletonManager03 {public static SingletonManager03 INSTANCE;private SingletonManager03() {}public static SingletonManager03 getInstance() {if (INSTANCE == null) {INSTANCE = new SingletonManager03();}return INSTANCE;}public static void main(String[] args) {SingletonManager03 instance1 = SingletonManager03.getInstance();SingletonManager03 instance2 = SingletonManager03.getInstance();System.out.println(instance1 == instance2);}
}
  • 验证这种方式的问题,模拟多线程模式,分析这种方式的问题

线程1执行到 instance == null时,这时实例还没实例化,线程2也刚好执行到instance == null,线程1和线程2初始化了两个不同实例对象。

为把问题模拟的更明显,在初始化之前,休眠1毫秒,模拟线程被打断,初始化不同的实例,效果更明显。

/*** @description: lazy loading 懒汉式加载,虽然达到了按需加载的目的,但带来了线程不安全的问题* @author: flygo* @time: 2022/7/4 09:32*/
public class SingletonManager03 {public static SingletonManager03 INSTANCE;private SingletonManager03() {}public static SingletonManager03 getInstance() {if (INSTANCE == null) {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}INSTANCE = new SingletonManager03();}return INSTANCE;}public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(() -> {System.out.println(SingletonManager03.getInstance().hashCode());}).start();}}
}

四、方式4

lazy loading 懒汉式加载,虽然达到了按需加载的目的,但带来了线程不安全的问题

通过synchronized加锁的方式解决,同时效率下降了

/*** @description: lazy loading 懒汉式加载,虽然达到了按需加载的目的,但带来了线程不安全的问题 <br>*     通过synchronized加锁的方式解决,同时效率下降了* @author: flygo* @time: 2022/7/4 09:32*/
public class SingletonManager04 {public static SingletonManager04 INSTANCE;private SingletonManager04() {}public static synchronized SingletonManager04 getInstance() {if (INSTANCE == null) {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}INSTANCE = new SingletonManager04();}return INSTANCE;}public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(() -> {System.out.println(SingletonManager04.getInstance().hashCode());}).start();}}
}

五、方式5(多线程有问题)

妄图通过减少同步代码块的方式提供效率,然后并不行。相当于没有加锁

/*** @description: lazy loading 懒汉式加载,虽然达到了按需加载的目的,但带来了线程不安全的问题 <br>*     通过synchronized加锁的方式解决,同时效率下降了* @author: flygo* @time: 2022/7/4 09:32*/
public class SingletonManager05 {public static SingletonManager05 INSTANCE;private SingletonManager05() {}public static SingletonManager05 getInstance() {if (INSTANCE == null) {// 妄图通过减少同步代码块的方式提供效率,然后并不行synchronized (SingletonManager05.class) {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}INSTANCE = new SingletonManager05();}}return INSTANCE;}public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(() -> {System.out.println(SingletonManager05.getInstance().hashCode());}).start();}}
}

六、方式6

使用双重检查

/*** @description: lazy loading 懒汉式加载,虽然达到了按需加载的目的,但带来了线程不安全的问题 <br>*     通过synchronized加锁的方式解决,同时效率下降了,增加双重检查* @author: flygo* @time: 2022/7/4 09:32*/
public class SingletonManager06 {// 需要加volatile,指令重排问题public static volatile SingletonManager06 INSTANCE;private SingletonManager06() {}public static SingletonManager06 getInstance() {if (INSTANCE == null) {// 双重检查synchronized (SingletonManager06.class) {if (INSTANCE == null) {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}INSTANCE = new SingletonManager06();}}}return INSTANCE;}public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(() -> {System.out.println(SingletonManager06.getInstance().hashCode());}).start();}}
}

七、方式7(完美的方式之一)

静态内部类的方式

JVM保证单例,加载外部类时,不会加载内部类,这样可以实现懒加载

/*** @description: 静态内部类的方式 <br>*     JVM保证单例,加载外部类时,不会加载内部类,这样可以实现懒加载* @author: flygo* @time: 2022/7/4 09:32*/
public class SingletonManager07 {private SingletonManager07() {}private static final class SingletonManager07Holder {private static final SingletonManager07 INSTANCE = new SingletonManager07();}public static SingletonManager07 getInstance() {return SingletonManager07Holder.INSTANCE;}public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(() -> {System.out.println(SingletonManager07.getInstance().hashCode());}).start();}}
}

八、方式8(完美中的完美)

不仅可以解决多线程同步,还可以解决反序列化问题

/*** @description: 不仅可以解决多线程同步,还可以解决反序列化问题 <br>* @author: flygo* @time: 2022/7/4 09:32*/
public enum SingletonManager08 {INSTANCE;public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(() -> {System.out.println(SingletonManager08.INSTANCE.hashCode());}).start();}}
}

九、源码地址

GitHub - jxaufang168/Design-Patterns: 设计模式学习设计模式学习. Contribute to jxaufang168/Design-Patterns development by creating an account on GitHub.icon-default.png?t=N7T8https://github.com/jxaufang168/Design-Patterns


 

这篇关于【设计模式-01】Singleton单利模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/584818

相关文章

Linux系统配置NAT网络模式的详细步骤(附图文)

《Linux系统配置NAT网络模式的详细步骤(附图文)》本文详细指导如何在VMware环境下配置NAT网络模式,包括设置主机和虚拟机的IP地址、网关,以及针对Linux和Windows系统的具体步骤,... 目录一、配置NAT网络模式二、设置虚拟机交换机网关2.1 打开虚拟机2.2 管理员授权2.3 设置子

SpringBoot如何通过Map实现策略模式

《SpringBoot如何通过Map实现策略模式》策略模式是一种行为设计模式,它允许在运行时选择算法的行为,在Spring框架中,我们可以利用@Resource注解和Map集合来优雅地实现策略模式,这... 目录前言底层机制解析Spring的集合类型自动装配@Resource注解的行为实现原理使用直接使用M

C#原型模式之如何通过克隆对象来优化创建过程

《C#原型模式之如何通过克隆对象来优化创建过程》原型模式是一种创建型设计模式,通过克隆现有对象来创建新对象,避免重复的创建成本和复杂的初始化过程,它适用于对象创建过程复杂、需要大量相似对象或避免重复初... 目录什么是原型模式?原型模式的工作原理C#中如何实现原型模式?1. 定义原型接口2. 实现原型接口3

大数据spark3.5安装部署之local模式详解

《大数据spark3.5安装部署之local模式详解》本文介绍了如何在本地模式下安装和配置Spark,并展示了如何使用SparkShell进行基本的数据处理操作,同时,还介绍了如何通过Spark-su... 目录下载上传解压配置jdk解压配置环境变量启动查看交互操作命令行提交应用spark,一个数据处理框架

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)

hdu 2602 and poj 3624(01背包)

01背包的模板题。 hdu2602代码: #include<stdio.h>#include<string.h>const int MaxN = 1001;int max(int a, int b){return a > b ? a : b;}int w[MaxN];int v[MaxN];int dp[MaxN];int main(){int T;int N, V;s

模版方法模式template method

学习笔记,原文链接 https://refactoringguru.cn/design-patterns/template-method 超类中定义了一个算法的框架, 允许子类在不修改结构的情况下重写算法的特定步骤。 上层接口有默认实现的方法和子类需要自己实现的方法

【iOS】MVC模式

MVC模式 MVC模式MVC模式demo MVC模式 MVC模式全称为model(模型)view(视图)controller(控制器),他分为三个不同的层分别负责不同的职责。 View:该层用于存放视图,该层中我们可以对页面及控件进行布局。Model:模型一般都拥有很好的可复用性,在该层中,我们可以统一管理一些数据。Controlller:该层充当一个CPU的功能,即该应用程序

迭代器模式iterator

学习笔记,原文链接 https://refactoringguru.cn/design-patterns/iterator 不暴露集合底层表现形式 (列表、 栈和树等) 的情况下遍历集合中所有的元素