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

编程入门 行业动态 更新时间:2024-10-26 04:22:14

【设计<a href=https://www.elefans.com/category/jswz/34/1771241.html style=模式】第4节:创建型模式之“单例模式”"/>

【设计模式】第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实现在初次使用这个实例时才加载的效果。

更多推荐

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

本文发布于:2023-12-03 11:04:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1654649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!