当前位置: 首页 > news >正文

【设计模式】第4节:创建型模式之“单例模式”

一、介绍

采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。

不使用单例模式的UML类图:

请添加图片描述

使用单例模式的UML类图:

请添加图片描述

使用场景:

  • 需要频繁创建或销毁的对象
  • 创建对象耗时过多或耗费资源过多,但又经常用到
  • 工具类对象
  • 频繁访问数据库或文件的对象

二、Java版实现

1. 饿汉式(静态常量)

//饿汉式(静态变量)
class Singleton {//1. 构造器私有化, 外部能newprivate Singleton() {}//2.本类内部创建对象实例private final static Singleton instance = new Singleton();//3. 提供一个公有的静态方法,返回实例对象public static Singleton getInstance() {return instance;}
}

优点:写法简单,在类装载的时候就完成了实例化,避免了线程同步问题。

缺点:在类加载的时候完成实例化,没有达到懒加载的效果,可能造成内存浪费。

2. 饿汉式(静态代码块)

//饿汉式(静态变量)
class Singleton {//1. 构造器私有化, 外部能newprivate Singleton() {}//2.本类内部创建对象实例private  static Singleton instance;static { // 在静态代码块中,创建单例对象instance = new Singleton();}//3. 提供一个公有的静态方法,返回实例对象public static Singleton getInstance() {return instance;}
}

优缺点同上。

3. 懒汉式(线程不安全)

class Singleton {private static Singleton instance;private Singleton() {}//提供一个静态的公有方法,当使用到该方法时,才去创建 instance//即懒汉式public static Singleton getInstance() {if(instance == null) {instance = new Singleton();}return instance;}
}

优缺点:起到了懒加载的效果,但只能在单线程下使用,多线程可能创建多个实例。

3. 懒汉式(线程安全,同步方法)

// 懒汉式(线程安全,同步方法)
class Singleton {private static Singleton instance;private Singleton() {}//提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题//即懒汉式public static synchronized Singleton getInstance() {if(instance == null) {instance = new Singleton();}return instance;}
}

优缺点:解决了线程安全问题,但效率太低,每个线程在想获得类的实例时候,都需要进行同步。

5. 双重检查

class Singleton {private static volatile Singleton instance;private Singleton() {}//提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题//同时保证了效率, 推荐使用public static synchronized Singleton getInstance() {if(instance == null) {synchronized (Singleton.class) {if(instance == null) {instance = new Singleton();}}}return instance;}
}

优缺点:实例代码只需要执行一次,后面再访问时,会被外层判空语句拦截,避免反复进行方法同步。延迟加载,效率较高。

6. 静态内部类

// 静态内部类完成, 推荐使用
class Singleton {private static volatile Singleton instance;//构造器私有化private Singleton() {}//写一个静态内部类,该类中有一个静态属性 Singletonprivate static class SingletonInstance {private static final Singleton INSTANCE = new Singleton(); }//提供一个静态的公有方法,直接返回SingletonInstance.INSTANCEpublic static synchronized Singleton getInstance() {return SingletonInstance.INSTANCE;}
}

静态内部类的特点:当外部类装载时,静态内部类不会立即实例化,而是在真正用到时才会实例化。并且静态内部类保证了线程的安全性。

7. 枚举

package com.atguigu.singleton.type8;public class SingletonTest08 {public static void main(String[] args) {Singleton instance = Singleton.INSTANCE;Singleton instance2 = Singleton.INSTANCE;System.out.println(instance == instance2);System.out.println(instance.hashCode());System.out.println(instance2.hashCode());instance.sayOK();}
}//使用枚举,可以实现单例, 推荐
enum Singleton {INSTANCE; //属性public void sayOK() {System.out.println("ok~");}
}

优缺点:不仅可以避免多线程同步问题,而且还能防止反序列化重新创建新的对象。

三、Golang版实现

1. 饿汉式

package mainimport "fmt"type Singleton struct {	Name string
}var SingletonInstance Singletonfunc init() {SingletonInstance = Singleton{"singleTonName"};
}func main() {fmt.Printf("SingletonInstance: %v", SingletonInstance)
}

通过init函数在初始化的时候加载单例类的实例。

2. 懒汉式

package mainimport ("fmt""sync"
)type Singleton struct {	Name string
}var (SingletonInstance SingletonSingletonOnce     sync.Once
)func GetInstance() Singleton {SingletonOnce.Do(func() {SingletonInstance = Singleton{"SingletonName"}})return SingletonInstance
}func main() {GetInstance()fmt.Printf("SingletonInstance: %v", SingletonInstance)
}

通过sync.Once实现在初次使用这个实例时才加载的效果。

http://www.lryc.cn/news/209134.html

相关文章:

  • NodeJS爬取墨刀上的设计图片
  • linux--
  • conda虚拟环境笔记收录
  • RGB-T Salient Object Detection via Fusing Multi-Level CNN Features
  • 安卓开发实例:方向传感器
  • [论文笔记]GTE
  • Prometheus字段解析
  • msigdbr hallmarks gsea broad研究所
  • 理解V3中的proxy和reflect
  • 实现寄生组合继承
  • ARM 账号注册报错 The claims exchange ‘Salesforce-UserWriteUsingEmail‘
  • 笔记:电子设备接地,接的到底是什么地?
  • PY32F002A系列单片机:高性价比、低功耗,满足多样化应用需求
  • 头歌的数据库的第三次作业的答案
  • 前端3D规划
  • appium操控微信小程序的坑
  • 6 个最佳 Windows 免费磁盘分区管理器
  • 【Leetcode】【每日一题】【简单】2558. 从数量最多的堆取走礼物
  • LeetCode 每日一题 2023/10/23-2023/10/29
  • Android:Installed Build Tools revision 33.0.2 is corrupted.
  • 语法复习之C语言与指针
  • vue笔记(二)
  • 【IT行业就业前景广阔:探讨热门方向与就业机会】
  • linux上java -jar方式运行项目及输出文件nohup.out的清理, linux上定时器的用法
  • macOS 12 Monterey v12.7.1正式版:开启全新的操作系统体验
  • vue制作防止用户未登录或未填写信息就跳转页面的路由拦截器
  • postgis ST_CoverageInvalidEdges用法
  • sqlalchemy的部分函数合集
  • mac苹果电脑使用日常
  • 多线程面试相关知识点