单例模式构造单例对象

单例模式(Singleton Pattern)是一个比较简单的模式,其定义如下:

确保某一个类 只有一个实例,而且自行实例化并向整个系统提供这个实例。

饿汉式创建单例:(饿汉式创建单例不存在线程安全以及指令重排等问题)

public class Singleton {
    private static final Singleton singleton = new Singleton();
    //限制产生多个对象
    private Singleton(){
    };

    //返回创建的单例对象(获取对象的方法一定要是static,不然永远获取不到。。。)
    public static Singleton getInstance(){
        return singleton;
    }

    public  void doSomething(){
        System.out.println("创建了一个单例对象,hashcode:" + this.hashCode());
    }
}
public class Main {
    public static void main(String[] args) {
        //两个相同对象的hashcode不一致
        Object o1 = new Object();
        Object o2 = new Object();
        System.out.println(o1.hashCode());
        System.out.println(o2.hashCode());
        //单例对象的hashcode一致
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        instance1.doSomething();
        instance2.doSomething();
    }
}

输出:
o1的hashcode:1554874502
o2的hashcode:1846274136
创建了一个单例对象,hashcode:1639705018
创建了一个单例对象,hashcode:1639705018

懒汉式创建单例模式(一定要加锁,并且双重校验,不然是线程不安全的)

public class Singleton2 {
    //volatile关键字防止指令重排
    private volatile static Singleton2 singleton2;

    //限制产生多个对象
    private Singleton2(){

    }

    public static Singleton2 getInstance(){
        if (null == singleton2){
            synchronized (Singleton2.class){
                //双重校验达到线程安全
                if (null == singleton2){
                    singleton2 = new Singleton2();
                }
            }
        }
        return singleton2;
    }

    public  void doSomething(){
        System.out.println("创建了一个单例对象,hashcode:" + this.hashCode());
    }
}
public class Main {
    public static void main(String[] args) {
        //两个相同对象的hashcode不一致
        Object o1 = new Object();
        Object o2 = new Object();
        System.out.println("o1的hashcode:" + o1.hashCode());
        System.out.println("o2的hashcode:" + o2.hashCode());
        //单例对象的hashcode一致
        Singleton2 instance1 = Singleton2.getInstance();
        Singleton2 instance2 = Singleton2.getInstance();
        instance1.doSomething();
        instance2.doSomething();
    }
}

输出:
o1的hashcode:1554874502
o2的hashcode:1846274136
创建了一个单例对象,hashcode:1639705018
创建了一个单例对象,hashcode:1639705018

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值