Java中单例模式的写法

文章介绍了单例模式的基本概念,即确保一个类只有一个实例。饿汉模式是在程序启动时就创建对象,而懒汉模式则在首次使用时才创建。饿汉模式保证线程安全,但可能会浪费资源;懒汉模式延迟加载,节省资源,但在多线程环境下需要同步控制。
摘要由CSDN通过智能技术生成

单例模式对应的场景就是整个程序中的对象只能new一次。可以达到上述单例模式的方法有很多,现只介绍饿汉模式和懒汉模式。

举个例子描述一下饿汉模式和懒汉模式:

假如一个编译器需要打开一个很大的文件,假设这个文件有100G,有的编译器会尝试把所有内容加载到内存中再显示出来(这就是饿汉模式);有的编译器则只加载当前一个屏幕所能显示到的内容,当用户翻到下一页时再加载下一页所需的内容(这就是懒汉模式,能不加载就不加载)。

一、饿汉模式

程序启动,类加载之后,立即创建出对象。

代码示例:

//饿汉模式
class Singleton{
    private static Singleton instance=new Singleton();
    public static Singleton getInstance(){
        return instance;
    }

    //做出一个限制,让构造方法称为private,限制别人new一个新对象
    private Singleton(){}
}
public class Demo4 {
    public static void main(String[] args) {
        Singleton s1=Singleton.getInstance();
        Singleton s2=Singleton.getInstance();

        System.out.println(s1==s2);
    }
}

此时运行代码,发现s1和s2是一个对象没输出true 

当在main方法中new一个新对象时,会报false

//饿汉模式
class Singleton{
    private static Singleton instance=new Singleton();
    public static Singleton getInstance(){
        return instance;
    }

    //做出一个限制,让构造方法称为private,限制别人new一个新对象
    private Singleton(){}
}
public class Demo4 {
    public static void main(String[] args) {
        Singleton s1=Singleton.getInstance();
        Singleton s2=Singleton.getInstance();
        
        //报红色波浪线显示错误
        Singleton s3=new Singleton();
        
        System.out.println(s1==s2);
    }
}

 二、懒汉模式。

程序启动,类加载之后,在第一次使用对象的时候再创建对象,否则能不创建就不创建。

代码示例:

//懒汉模式
class SingletonLazy{
    private static volatile SingletonLazy instance=null;
    public static SingletonLazy getInstance(){
        //3.判断是不是第一次进行if判断,如果是第一次进行加锁,避免后续加锁而降低效率
        if(instance==null){
            //2.加锁,使if判断和创建新对象成为一个整体,具有原子性
            synchronized (SingletonLazy.class){
                //1.基础代码
                if (instance==null){
                    instance=new SingletonLazy();
                }
            }
        }
        return instance;
    }
    private SingletonLazy(){}
}
public class Demo5 {
    public static void main(String[] args) {
        SingletonLazy s1=SingletonLazy.getInstance();
        SingletonLazy s2=SingletonLazy.getInstance();
        
        //报错
        SingletonLazy s3=new SingletonLazy();

        System.out.println(s1==s2);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值