单例模式-Java实现

简单原理介绍

        单例模式保证了一个类只有一个实例,并且提供了一个访问它的全局访问点。

作用

        单例模式主要是为了解决一个全局使用的类频繁地创建与销毁。之前介绍JVM的时候有提到Java的内存结构,通过类实例化的对象一般都是放在堆内存中的,频繁的创建对象会使得堆内存不够用,进而触发垃圾回收,这是会影响性能的。(简单解释下这里,这个情况就像你在家里吃零食,垃圾扔的到处都是,你妈进来收拾屋子,肯定会让你先别吃了,然后清理。回到这里,吃零食就是创建对象,所以垃圾清理时JVM中的进程会先停止工作(stop-the-world),反映到用户层面就是系统卡顿了

代码

package 设计模式.单例模式;/*** Created by 姜水桦 on 2023/11/25 20:26* 功能描述: 实例化时机* 饿汉式 懒汉式 加锁(避免多线程都进行实例化)*/
public class SingletonPattern {public static void main(String[] args) {}static class Singleton{private static Singleton singleton;
//        private static Singleton singleton = new Singleton(); //饿汉式 加载时直接获取实例private Singleton(){}public synchronized static Singleton getInstance1(){ //synchronized 加锁if (singleton == null) {singleton = new Singleton(); //懒汉式 懒加载}return singleton;}public static Singleton getInstance(){ //双重检查锁if (singleton == null) {synchronized(Singleton.class){if (singleton == null) {singleton = new Singleton();}}}return singleton;}}
}