单例设计模式

一、饿汉式(线程同步)

优点:线程安全
缺点:在类加载的时候就已经实例化,没有达到懒加载的效果,若是没有使用实例,则就造成内存的浪费

1、静态常量
/**
 * 饿汉式一
 */
public class Singleton01 {

    private Singleton01() {}

    private static Singleton01 instance = new Singleton01();

    public Singleton01 getInstance(){
        return instance;
    }
}
2、静态代码块
/**
 * 饿汉式二
 */
public class Singleton02 {
    private static Singleton02 instance;
    static{
        instance = new Singleton02();
    }
    
    private Singleton02() {}
    
    public Singleton02 getInstance(){
        return instance;
    }
}

二、懒汉式

1、懒汉式(线程不安全)

优点:实现了懒加载的效果
缺点:在多线程中,如果线程1调用方法在判断是空进去后,资源被其他线程抢占,其他线程也调用该方法,此时该对象还未实例化,则可以通过判断创建实例,之后线程1重新拿回资源继续运行,则又再次创建了一个实例,导致了创建多个实例。

/**
 * 懒汉式一
 * 线程不安全,仅适用于单线程
 */
public class Singleton03 {
    private Singleton03() {}

    private static Singleton03 instance;

    public static Singleton03 getInstance(){
        if (instance == null){
            instance = new Singleton03();
        }
        return instance;
    }
}
2、懒汉式(线程安全效率低)

优点:通过同步方法解决了线程安全问题
缺点:运行效率低,此方法只需调用一次实例化即可,在之后每次调用该方法都只需返回即可,但是在调用该方法时还要同步。

/**
 * 懒汉式二
 * 线程安全
 * 效率低
 */
public class Singleton04 {
    private Singleton04() {}

    private static Singleton04 instance;

    public synchronized static Singleton04 getInstance(){
        if (instance == null){
            instance = new Singleton04();
        }
        return instance;
    }
}

3、懒汉式(线程安全,多重判断)

优点:通过使用同步代码块以及多重判断解决了线程安全问题;
同时在实例化之后也只需判断返回即可,提高了效率;
也实现了懒加载的效果。

/**
 * 懒汉式三
 * 线程安全
 * 推荐使用
 */
public class Singleton05 {
    private Singleton05() {}

    private static Singleton05 instance;

    public static Singleton05 getInstance(){
        if (instance == null){
            synchronized (Singleton05.class){
                if (instance == null){
                    instance = new Singleton05();
                }
            }
        }
        return instance;
    }
}

三、静态内部类

优点:避免了线程不安全,利用静态内部类特点实现延迟加载,效率高

/**
 * 静态内部类
 * 利用jvm的类加载机制保证了线程安全和懒加载
 * 推荐使用
 */
public class Singleton06 {
    private Singleton06() {}

    private static class SingletonInstance {
        private static final Singleton06 INSTANCE = new Singleton06();
    }
    
    public static Singleton06 getInstance(){
        return SingletonInstance.INSTANCE;
    }
}

四、枚举方式

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

/**
* 推荐使用枚举
*/
public enum Singleton07 {
    INSTANCE;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值