单例模式(饿汉模式与懒汉模式)

单例模式(饿汉模式与懒汉模式)

描述:一个类永远只有一个实例(对象)
作用:节约内存,提高性能。比如:电脑的任务管理器。因为对象越多,占的内存越大,容易造成内存溢出。
1.饿汉单例模式(对象已经创建好了,要用就直接用)
步骤a.定义一个类,把构造器私有
b.定义一个静态变量储存一个对象
c.提供一个静态返回单例对象方法

class SingleInstance01{
    /**
     b.定义一个静态变量存储一个对象。
         饿汉: 对象已经提前创建好了。
     */
    public static SingleInstance01 intance = new SingleInstance01();

    /**
     a.定义一个类,把构造器私有。
     */
    private SingleInstance01(){
    }

    /**
     c.提供一个返回单例对象的方法。
     */

    public static SingleInstance01 getInstance(){
        return intance;
    }

}
/**
 * 测试类
 */
public class SingleInstanceDemo01 {
    public static void main(String[] args) {

        SingleInstance01 s1 = SingleInstance01.intance;
        SingleInstance01 s2 = SingleInstance01.getInstance();
        System.out.println(s1 == s2); // true
    }
}

2.懒汉模式(对象还没创建好,要用的时候才创建)
步骤:和饿汉步骤一样,区别只是前者提前创建好对象,后者真正用的时候才去创建对象

class SingleInstance02{
    /**
     b.定义一个静态变量存储一个对象。
     */              
    private static SingleInstance02 instance;
    /**
     a.定义一个类,把构造器私有。
     */
    private SingleInstance02(){
    }
    /**
     c.提供一个返回单例对象的方法。
     */
    public static SingleInstance02 getInstance(){
        if(instance == null){
            // 判断是否第一次,是第一次就创建对象
            instance = new SingleInstance02();
        }
        return instance;
    }
}
/**
*测试类
 */
public class SingleInstanceDemo02 {
    public static void main(String[] args) {
        SingleInstance02 instance1 = SingleInstance02.getInstance();
        SingleInstance02 instance2 = SingleInstance02.getInstance();
        System.out.println(instance1 == instance2); // true
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值