0
点赞
收藏
分享

微信扫一扫

java 单例模式 ---饿汉式懒汉式

无愠色 2022-01-28 阅读 65

饿汉式

饿汉式:在程序启动或单例模式类被加载的时候,单例模式实例就已经被创建。

 上例子!

package com.happy.demo;


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

  happy h1 = happy.getInstance();
  happy h2 = happy.getInstance();
  System.out.println(h1 == h2);//true
  }
}
//this is 饿汉式~
class happy{
   //1.私有化类的构造器
  private happy(){

  }
  
  //2.内部创建类的对象
  //3.要求此对象也必须声明为静态的
  private static happy instance = new happy();

  //4.提供公共的静态的方法,返回类的对象
  public static happy getInstance(){
      return instance;
  }
}

懒汉式

懒汉式:当程序第一次访问单例模式实例时才进行创建。

废话不多说,上代码!

package com.happy.demo;


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

  nice h1 = nice.getInstance();
  nice h2 = nice.getInstance();
  System.out.println(h1 == h2);//true
  }
}
//this is 懒汉式~
class nice{
   //1.私有化类的构造器
  private nice(){

  }
  
  //2.声明当前类对象,没有初始化
  //3.要求此对象也必须声明为static的
  private static nice instance = null;

  //4.声明public,static的放回当前类对象的方法
  public static nice getInstance(){
	  if(instance == null){
		  instance = new nice();
	  }
      return instance;
  }
}

饿汉式vs懒汉式

 注意:如果一个对象使用频率不高,占用内存还特别大,明显就不合适用饿汉式了,这时就需要一种懒加载的思想,当程序需要这个实例的时候才去创建对象,就如同一个人懒的饿到不行了才去吃东西。

结语

举报

相关推荐

0 条评论