Java设计模式——单列模式

    xiaoxiao2021-04-18  60

    1.定义:

    保证一个类仅有一个实例,并提供一个访问它的全局访问点。

    2.说明及分类:

    负责创建Singleton类自己的唯一实例,并提供一个getInstance的方法,让外部来访问这个类的唯一实例。

    (1)饿汉式: private static Singleton uniqueInstance = new Singleton(); (2)懒汉式: private static Singleton uniqueInstance = null;

    3.功能:

    单例模式是用来保证这个类在运行期间只会被创建一个类实例,另外单例还提供了一个全局唯一访问这个类实例的访问点,就是getInstance方法。

    4.使用范围:

    Java里面实现的单例是一个虚拟机的范围。因为装载类的功能是虚拟机的,所以一个虚拟机在通过自己的ClassLoader装载饿汉式实现单例类的时候就会创建一个类的实例。 备注:懒汉式单例具有延迟加载和缓存的思想。

    5.优缺点:

    (1)懒汉式是典型的时间换空间; (2)饿汉式是典型的空间换时间。 package com.singleton.demo; /** * 七种方式实现单例模式 * */ public class SingletonDemo { /** * 单例模式,懒汉式,线程安全 * */ @SuppressWarnings("unused") private static class Singleton1 { private final static Singleton1 INSTANCE = new Singleton1(); private Singleton1() { } public static Singleton1 getInstance() { return INSTANCE; } } /** * 单例模式,懒汉式,线程不安全 * */ public static class Singleton2 { private static Singleton2 instance = null; private Singleton2() { } public static Singleton2 getInstance() { if (instance == null) { instance = new Singleton2(); } return instance; } } /** * 单例模式,饿汉式,线程安全,多线程环境下效率不高 * */ public static class Singleton3 { private static Singleton3 instance = null; private Singleton3() { } public static synchronized Singleton3 getInstance() { if (instance == null) { instance = new Singleton3(); } return instance; } } /** * 单例模式,懒汉式,变种,线程安全 * */ public static class Singleton4 { private static Singleton4 instance = null; static { instance = new Singleton4(); } private Singleton4() { } public static Singleton4 getInstance() { return instance; } } /** * 单例模式,使用静态内部类,线程安全(推荐使用) * */ public static class Singleton5 { private final static class SingletonHolder { private static final Singleton5 INSTANCE = new Singleton5(); } @SuppressWarnings("unused") private static Singleton5 getInstance() { return SingletonHolder.INSTANCE; } } /** * 静态内部类,使用枚举方式,线程安全(推荐使用) * */ public enum Singleton6 { INSTANCE; public void whateverMethod() { } } /** * 静态内部类,使用双重校验锁,线程安全(推荐使用) * */ public static class Singleton7 { private volatile static Singleton7 instance = null; private Singleton7() { } public static Singleton7 getInstance() { if (instance == null) { synchronized (Singleton7.class) { if (instance == null) { instance = new Singleton7(); } } } return instance; } } }

    转载请注明原文地址: https://ju.6miu.com/read-674999.html

    最新回复(0)