单例设计模式

本文介绍了Java中的两种单例模式实现:饿汉式和懒汉式。饿汉式在类加载时即创建对象,线程安全但可能导致资源浪费;懒汉式则在首次调用时创建对象,线程不安全但更节省资源。Java.lang.Runtime类作为单例模式的经典实例被提及。
摘要由CSDN通过智能技术生成

单例模式应用实例:

饿汉式步骤如下:(对象还没使用就已经创建了对象)

1)构造器私有化    (防止直接new)

2)类的内部创建对象

3)向外部暴露一个静态的公共方法

4)代码实现

饿汉式单例实例:

public class SingleTon01 {
    public static void main(String[] args) {
//        GirFriend girFriend1 = new GirFriend("小红");
//        GirFriend girFriend2 = new GirFriend("小花");
        GirFriend instance = GirFriend.getInstance();
        System.out.println(instance.toString());
    }
}

//一个GirFriend类
class GirFriend {

    private String name;

    private static GirFriend gf = new GirFriend("小红");

    //如何保障我们只能创建一个GirFriend对象
    //步骤【单例模式-饿汉式】:
    //1.将构造器私有化
    //2.在类的内部直接创建一个私有的对象
    //3.再提供一个公共的 static 方法,返回 gf对象
    private GirFriend(String name) {
        this.name = name;
    }

    public static GirFriend getInstance() {
        return gf;
    }

    @Override
    public String toString() {
        return name;
    }
}

懒汉式单例实例:

public class SingleTon02 {
    public static void main(String[] args) {

        Cat instance1 = Cat.getInstance();
        System.out.println(instance1);

        System.out.println("-----------------------------");

        Cat instance2 = Cat.getInstance();
        System.out.println(instance2);

        System.out.println(instance1 == instance2);
    }

}


//创建一个Cat对象
class Cat{
    private String name;
    private static Cat cat;

    //步骤【单例模式-懒汉式】:
    //1.构造器私有化
    //2.定义一个 static 静态属性对象
    //3.提供一个public的 static方法 ,可以返回一个Cat对象
    //4.懒汉式,只当用户调用getInstance()时,才会返回对象,后面再次调用时,会返回上次创建的 cat 对象,从而保证了单例
    private Cat(String name){
        this.name = name;
        System.out.println("构造器被调用...");
    }

    public static Cat getInstance(){

        if (cat == null){//如果没有创建cat对象
            cat = new Cat("小可爱");
        }
        return cat;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                '}';
    }
}



运行结果:

构造器被调用...
Cat{name='小可爱'}
-----------------------------
Cat{name='小可爱'}
true

进程已结束,退出代码0

饿汉式VS懒汉式:

1.二者主要的区别在于创建对象的时机不同:饿汉式是在类加载就创建了对象实例,而懒汉式是在使用时才创建。

2.饿汉式不存在线程安全问题,懒汉式存在线程安全问题。

3.饿汉式存在浪费资源的可能。应为如果程序员一个对象实例都没有使用,那么饿汉式创建的对象就浪费了,懒汉式是使用时才创建,就不存在这个问题。

4.在JavaSE标准类中,java.lang.Runtime就是经典的单例模式。

//观看老韩视频总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值