单例模式

单例模式是指该类只能有一个实例,并且该实例只有由该类自己创建。

在jdk中,Runtime就是一个很典型的单例模式。

单例设计模式一般有两种实现方式:

饿汉模式

饿汉模式是指该类在加载的过程中,就已经生成对应的实例,Runtime类就是基于饿汉模式实现的单例,因为饿汉模式是在类加载的过程中产生实例,因此,饿汉模式本身就是线程安全的,可以使用在多线程情况下。

实现方式:

public class Hungry {

    private static Hungry hungry = new Hungry();

    private Hungry() {
    }

    public static Hungry getHungry() {
        return hungry;
    }

    public void display() {
        System.out.println("this is Hungry");
    }

}

懒汉模式

懒汉模式,顾名思义,在使用的时候才去创建对应的实例,因此,懒汉模式在多线程的场景中,需要使用volatile或者synchronized来保证线程安全。

public class Lazy {
    private Lazy() {
    }

    private static volatile Lazy lazy;

    public static synchronized Lazy getLazy() {
        if (lazy == null) {
            lazy = new Lazy();
        }
        return lazy;
    }

    public void display() {
        System.out.println("this is Lazy");
    }
}

测试代码:

public class Singleton {

    public static void main(String agrs[]) {
        Hungry.getHungry().display();
        Lazy.getLazy().display();
    }

}

输出:

this is Hungry
this is Lazy

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值