单例设计模式

本文介绍了Java中两种常见的单例模式实现方式:饿汉式和懒汉式。饿汉式在类加载时就完成了实例化,线程安全但可能导致资源浪费;懒汉式则在首次调用时才实例化,实现了按需加载,但在多线程环境下需要额外的同步措施。文中通过代码示例展示了这两种方式的实现细节,并分析了它们的优缺点。
摘要由CSDN通过智能技术生成

1、饿汉式

public class HungryTest {
    public static void main(String[] args) {
        HungrySingleton hungrySingleton1 = HungrySingleton.getInstance();
        HungrySingleton hungrySingleton2 = HungrySingleton.getInstance();
        System.out.println(hungrySingleton1 == hungrySingleton2); //true 同一个对象
    }
}

// 饿汉式写法
class HungrySingleton {
    // 1.私有化构造器
    private HungrySingleton() {
    }

    // 2.内部创建类的对象,对象为静态的
    private static HungrySingleton instance = new HungrySingleton();

    // 3.提供共用的静态的方法,返回类的对象
    public static HungrySingleton getInstance() {
        return instance;
    }
}

2、懒汉式

public class LazyTest {
    public static void main(String[] args) {
        LazySingleton lazySingleton1 = LazySingleton.getInstance();
        LazySingleton lazySingleton2 = LazySingleton.getInstance();
        System.out.println(lazySingleton1 == lazySingleton2); //true 同一个对象
    }
}

// 懒汉式写法
class LazySingleton {
    // 1.私有化构造器
    private LazySingleton() {
    }

    // 2.声明当前类的对象,没有初始化。对象为静态的
    private static LazySingleton instance = null;

    // 3.提供共用的静态的方法,返回类的对象
    public static LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

// 懒汉式写法:线程安全+效率高
class LazySingleton2 {
    private LazySingleton2() {
    }
    private static LazySingleton2 instance = null;

    public static LazySingleton2 getInstance() {
        if (instance == null) {

            synchronized (LazySingleton2.class) { // 因为是静态方法,不能使用this
                if (instance == null) {
                    instance = new LazySingleton2();
                }
            }
        }
        return instance;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值