单例设计模式(两种)

本文介绍了Java中的两种单例设计模式:饿汉式和懒汉式。饿汉式在类加载时即创建对象,而懒汉式则在第一次调用getInstance()时创建,后续调用返回同一对象。两者都确保了类只会创建一个实例,但懒汉式更注重延迟加载。
摘要由CSDN通过智能技术生成

单例设计模式(两种)

饿汉式

  • 可能造成创建了对象但是没有使用(弊端)
  • 没有去使用就创建实例
  • 随着类的加载而创建
package com.xz.single_;

public class SingleTon01 {
    public static void main(String[] args) {
        GirlFriend instance1 = GirlFriend.getInstance();
        System.out.println(instance1);
        //GirlFriend类只会被加载一次,所以即使再创建,都是同一个对象
        GirlFriend instance2 = GirlFriend.getInstance();
        System.out.println(instance2);
        //验证
        System.out.println(instance1 == instance2);//true

        //System.out.println(BoyFriend.getInstance());
    }
}

class GirlFriend {
    private String name;
    //为了能够在静态方法中, 返回 gf 对象,需要将其修饰为static
    private static GirlFriend gf = new GirlFriend("小红");

    //如何保证我们只能创建一个 GirlFriend 对象
    //步骤
    //1.将构造器私有化
    //2.在类的内部直接创建
    //3.提供一个公共的static方法, 返回 gf 对象
    private GirlFriend(String name) {
        this.name = name;
    }

    public static GirlFriend getInstance() {
        return gf;
    }

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

class BoyFriend {
    private String name;
    private static BoyFriend bf = new BoyFriend("小帅");

    private BoyFriend(String name) {
        this.name = name;
    }

    public static BoyFriend getInstance() {
        return bf;
    }

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

懒汉式

  • 演示懒汉式的单例模式

  • 程序在运行中,只能创建一个对象

  • 不会随着类的加载创建对象

  • 只有当用户使用getInstance()时,才返回对象,后面再次调用是,会返回上次创建的对象

    步骤

    1. 构造器私有化
    2. 定义一个static静态属性对象
    3. 提供一个public的static方法,可以返回一个对象
package com.xz.single_;

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

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

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

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

class Cat {
    private String name;
    private static Cat cat;

    private Cat(String name) {
        this.name = name;
    }

    public static Cat getInstance() {
        if (cat == null) {
            cat = new Cat("小可爱");
        }
        return cat;
    }

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

区别

请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员正正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值