Java中设计模式之单例模式

    xiaoxiao2022-07-13  157

    package com.lzw.singleton; /** * 饿汉式 静态常量 -- 可用 * 优点:简单;在类装载的时候就完成实例化;避免了线程同步问题 * 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费 * @author lzw * @Date 2019年5月23日 */ public class Singleton { private final static Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } } /** * 饿汉式 静态代码块 -- 可用 * 分析:同上面的方式类似,这里将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例;所以优缺点基本相同 * @author lzw * @Date 2019年5月23日 */ class Singleton2 { private static Singleton2 instance; static { instance = new Singleton2(); } private Singleton2() {} public static Singleton2 getInstance() { return instance; } } /** * 懒汉式 线程不安全 -- 不可用 * 分析:这种起到了Lazy Loading的效果,但是只能在单线程下使用。多线程环境下是可不使用的。 * 原因:如果在多线程下,一个线程进入了if (singleton3 == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。 * @author lzw * @Date 2019年5月23日 */ class Singleton3{ private static Singleton3 singleton3; private Singleton3(){}; public static Singleton3 getSingleton3(){ if (singleton3 == null) { singleton3 = new Singleton3(); } return singleton3; } } /*** * 懒汉式 同步方法 线程安全 -- 不推荐使用 * 缺点:缺点:效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,直接return就行了 * @author lzw * @Date 2019年5月23日 */ class Singleton4 { private static Singleton4 singleton4; private Singleton4() {} public static synchronized Singleton4 getInstance() { if (singleton4 == null) { singleton4 = new Singleton4(); } return singleton4; } } /** * 懒汉式 同步代码块 线程安全 -- 不推荐使用 * @author lzw * @Date 2019年5月23日 */ class Singleton5 { private static Singleton5 singleton5; private Singleton5() {} public static Singleton5 getInstance() { if (singleton5 == null) { synchronized (Singleton.class) { singleton5 = new Singleton5(); } } return singleton5; } } /** * 双重检查 -- 推荐使用 * 优点:线程安全;延迟加载;效率较高 * @author lzw * @Date 2019年5月23日 */ class Singleton6 { private static volatile Singleton6 singleton6; private Singleton6() {} public static Singleton6 getInstance() { if (singleton6 == null) { synchronized (Singleton6.class) { if (singleton6 == null) { singleton6 = new Singleton6(); } } } return singleton6; } } /** * 静态内部类 -- 推荐使用 * 优点:避免了线程不安全,延迟加载,效率高 * @author lzw * @Date 2019年5月23日 */ class Singleton7 { private static volatile Singleton7 singleton7; private Singleton7() {} public static Singleton7 getInstance() { if (singleton7 == null) { synchronized (Singleton.class) { if (singleton7 == null) { singleton7 = new Singleton7(); } } } return singleton7; } } /** * 枚举 -- 可用 * 分析:在项目用的少 * @author lzw * @Date 2019年5月23日 */ enum Singleton8 { INSTANCE; public void whateverMethod() { System.out.println("我是枚举单利模式"); } }

     

    最新回复(0)