【JAVA】设计模式之单例模式

前言

java最常见的设计模式就是单例模式,而单例模式最常见的就是懒汉式和饿汉式,现在就分别看一下

 

1.懒汉式

懒汉式比较懒,当别人用到时才会初始化实例,而当有多个人同时用到就可能产生多个实例,造成线程安全问题。

public class Lazy {
  private static Lazy lazy;

  private Lazy(){

  }

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

 

2.饿汉式

饿汉式比较饿,在别人没有使用时就是先准备好了一份食物,因此别人来拿的时候都是它自己这一份食物,所以不存在线程安全问题。

public class Hungry {
private static Hungry hungry = new Hungry();

private Hungry(){

}


public static Hungry getHungry() {
return hungry;
}
}

 

posted @ 2018-12-26 23:01  键盘AQ  阅读(124)  评论(0编辑  收藏  举报