Java-单例-设计模式(一)

普通懒汉

/**
 * @author ctl
 * @date 2021/1/10
 * 单例模式 懒汉,非线程安全
 */
public class Singleton {

    private static Singleton instance = null;

    private Singleton() {
    }

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

线程安全懒汉

/**
 * @author ctl
 * @date 2021/1/10
 * 懒汉,线程安全,效率低下
 */
public class Singleton2 {

    private static Singleton2 instance;

    private Singleton2() {
    }

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

饿汉

/**
 * @author ctl
 * @date 2021/1/10
 * 饿汉,加载时就创建,无法做到懒加载,消耗资源
 */
public class Singleton3 {

    private static Singleton3 instance = new Singleton3();

    private Singleton3() {
    }

    public static Singleton3 getInstance() {
        return instance;
    }
}
/**
 * @author ctl
 * @date 2021/1/10
 * 饿汉,也是加载时就创建,跟上一种区别不大
 */
public class Singleton4 {

    private static Singleton4 instance = null;

    static {
        instance = new Singleton4();
    }

    private Singleton4() {
    }

    public static Singleton4 getInstance() {
        return instance;
    }
}

静态内部类

/**
 * @author ctl
 * @date 2021/1/10
 * 静态内部类,可以做到懒加载
 */
public class Singleton5 {

    private static class SingletonHolder {
        private static final Singleton5 INSTANCE = new Singleton5();
    }

    private Singleton5() {
    }

    public static final Singleton5 getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

枚举

/**
 * @author ctl
 * @date 2021/1/10
 * 枚举,写法简单,但使用不多
 */
public enum Singleton6 {

    INSTANCE;

    public void whateverMethod() {
    }
}

双重检查

/**
 * @author ctl
 * @date 2021/1/10
 * 双重检查
 */
public class Singleton7 {

	// volatile避免指令重排
    private volatile static Singleton7 instance;

    private Singleton7() {

    }

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

总结

其实还有很多变种的写法,很难说哪一种写法就是最完美的,了解原理即可,实际业务中可以根据不同的场景来做取舍和扩展,或者直接使用成熟的框架来管理,避免重复造轮子。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值