【设计模式】单例模式的5种实现(饿汉式、懒汉式、双检锁、静态内部类、枚举)

饿汉式

/**
 * 饿汉式:直接创建好对象实例,调用直接返回,不能延迟加载
 */
public class Singleton {
    private static final Singleton singleton = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return singleton;
    }
}

懒汉式

/**
 * 懒汉式:在获取实例时判断对象是否存在决定创建还是直接返回,因为有synchronized,并发高性能差
 */
public class Singleton2 {
    private static Singleton2 singleton;

    private Singleton2() {
    }

    // 对整个方法加锁
    public synchronized static Singleton2 getInstance() {
        if (singleton == null) {
            singleton = new Singleton2();
        }
        return singleton;
    }
}

懒汉式双检锁

/**
 * 懒汉式优化:双检锁,降低锁的粒度,只有实例是空才会加锁
 */
public class Singleton3 {
    private static volatile Singleton3 singleton;

    private Singleton3() {
    }

    public static Singleton3 getInstance() {
        if (singleton == null) {
            // 如果为空,获取锁
            synchronized (Singleton3.class) {
                // 如果依旧为空,创建对象
                if (singleton == null) {
                    singleton = new Singleton3();
                }
            }
        }
        return singleton;
    }
}

静态内部类

/**
 * 静态内部类:加载内部类的时候才会创建对象,可以延迟加载
 */
public class Singleton4 {

    private Singleton4() {
    }

    private static class SingletonInstance {
        private static final Singleton4 singleton = new Singleton4();
    }

    public static Singleton4 getInstance() {
        return SingletonInstance.singleton;
    }
}

枚举

/**
 * 枚举
 */
public enum Singleton5 {
    INSTANCE;

    public static Singleton5 getInstance() {
        return INSTANCE;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值