Skip to main content

单例设计模式

单例设计模式

饿汉式

  1. 构造器私有化 =》 防止直接 new
  2. 类的内部创建对象
  3. 向外暴露一个静态的公共方法 getInstance
  4. 代码实现

class GirlFriend{
private String name;
private GirlFriend gf = new GirFriend("wx");
private GirFiend(String name){
this.name = name;
}
public static GirFriend getInstance() {
return gf;
}
}

懒汉式

  1. 仍然构造器私有化
  2. 定义一个static静态属性对象
  3. 提供一个public的static方法 ,可以返回一个cat对象
// 希望在程序运行的过程中, 只能创建一个cat对象
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("Tom")
}
return cat;
}
}

对比

  1. 二者最主要的去呗在与创建对象的时机不同: 饿汉式式在类加载就创建了对象实例,而懒汉式是在使用时才创建。
  2. 饿汉式不存在线程安全问题,懒汉式存在线程安全问题。
  3. 饿汉式存在浪费资源可能,因为如果吃宵夜一个对象实例都没有使用,那么饿汉式创建的对象就浪费了, 懒汉式式是使用才创建,就不存在这个问题。
  4. 在javaSE标准类中, java.lang.Runtime就是经典的单例模式。