Java单例模式:饿汉式&懒汉式

这里写的单例模式分为饿汉式,懒汉式。

单例模式的特点:
1.只能有一个实例。
2.自己内部创建了一个唯一的实例。
3.给其它对象提供自己内部创建了的这个实例
单例模式就是”单一实例“,表现为”同一时间内,某个类的对象只有一个!“。饿汉式早早创建对象,随时可以使用(建议使用饿汉式的,随着年代的++,硬件物质变得富有,一般不在乎这一点点空间,而且一般都会创建对象的,只是使用对象的时间点不同早晚创建一点而已!)

饿汉式:

可以看到类被加载时,就直接创建了对象,此时也许并不需要获取对象,但是他也已经创建好了,会浪费空间,但是在使用的是后会快一点,也就是以空间来换取时间,饿汉式的线程是安全的。(因为已经有对象,把已有的对象看作是“饼子”可以随时满足吃的欲望,所以为饿汉式)

package Singleton;
//饿汉式,先创建实例,不管用不用以空间换时间!!(第一次加载快)
public class SingletonHunger {
    //1、私有构造
    private SingletonHunger(){

    }
    //2、私有静态实例化(饿汉式:直接实例化)
    private static SingletonHunger one = new SingletonHunger();

    //3、共有静态方法(公有:要将实例带出)
    public static SingletonHunger getOne(){
        return  one;
    }
}

懒汉式:

特点是“不到逼不得已“不会创建对象,可以把看成很懒。懒汉式线程不安全

package Singleton;

public class SingletonLazy {

    private SingletonLazy(){}

    private  static  SingletonLazy two;
//创建开放静态方法,并且实例化对象!!
    public static SingletonLazy getTwo(){
        if (two == null) {
            two=new SingletonLazy();
            return two;
        }
        return  two;

    }
}

线程不安全的解决方法:

package Singleton;

public class SingletonLazy {

    private static SingletonLazy two;

    private SingletonLazy() {
    }

    //创建开放静态方法,并且实例化对象!!
    public static SingletonLazy getTwo() {
        if (two == null) {//判断是否有必要加锁(没有该判断效率可能会偏低)
            synchronized ("java") {
                if (two == null) {//判断是否创建对象,如果没有该判断,可能会创建多个对象
                    two = new SingletonLazy();
                    return two;
                }
            }
        }
        return two;

    }
}

测试:

package Singleton;

public class Test {
    public static void main(String[] args) {
        SingletonHunger A=SingletonHunger.getOne();
        SingletonHunger B=SingletonHunger.getOne();
        System.out.println(A);
        System.out.println(B);

        SingletonLazy C=SingletonLazy.getTwo();
        SingletonLazy D=SingletonLazy.getTwo();
        System.out.println(C);
        System.out.println(D);
    }
}

运行的结果会得出,A、B是同一个实例,C、D是同一个实例。

程序员初成长路线:(很全面的学习视频,网址…点击查看)https://blog.csdn.net/qq_43541242/article/details/107165068

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值