0
点赞
收藏
分享

微信扫一扫

单例模式:饿汉式

  • ​饿汉式(静态常量)​

1) 构造器私有化 (防止 new )
2) 类的内部创建对象
3) 向外暴露一个静态的公共方法。getInstance

  • 代码实现

package com.atguigu.singleton.type1;

public class SingletonTest01 {

public static void main(String[] args) {
//测试
Singleton instance = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println(instance == instance2); // true
System.out.println("instance.hashCode=" + instance.hashCode());
System.out.println("instance2.hashCode=" + instance2.hashCode());
}

}

//饿汉式(静态变量)
class Singleton {

//1. 构造器私有化, 外部不能new
private Singleton() {

}

//2.本类内部创建对象实例
private final static Singleton instance = new Singleton();

//3. 提供一个公有的静态方法,返回实例对象
public static Singleton getInstance() {
return instance;
}

}

  • 优缺点说明

1) 优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
2) 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费
3) 这种方式基于classloder机制避免了多线程的同步问题,不过,instance在类装载时就实例化,在单例模式中大多数都是调用getInstance方法,
但是导致类装载的原因有很多种,因此不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化instance就没有达到lazy loading的效果
4) 结论:这种单例模式可用,可能造成内存浪费

  • ​饿汉式(静态代码块)​
  • 代码实现

package com.atguigu.singleton.type2;

public class SingletonTest02 {

public static void main(String[] args) {
//测试
Singleton instance = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println(instance == instance2); // true
System.out.println("instance.hashCode=" + instance.hashCode());
System.out.println("instance2.hashCode=" + instance2.hashCode());
}

}

//饿汉式(静态变量)
class Singleton {

//1. 构造器私有化, 外部不能new
private Singleton() {

}

//2.本类内部创建对象实例
private static Singleton instance;

static { // 在静态代码块中,创建单例对象
instance = new Singleton();
}

//3. 提供一个公有的静态方法,返回实例对象
public static Singleton getInstance() {
return instance;
}

}

  • 优缺点说明

1) 这种方式和上面的方式其实类似,只不过将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例。优缺点和上面是一样的。
2) 结论:这种单例模式可用,但是可能造成内存浪费



举报

相关推荐

0 条评论