定义

是一种常用的软件设计模式,一个类再一个jvm中只有一个实例。

优缺点

在内存里只有一个实例,减少了内存的开销,尤其是频繁的创建和销毁实例;避免对资源的多重占用
不适用于变化的对象

创建方式

饿汉式 - 提前创建好,用到时候直接取

  1. -- 是否为线程安全的 ?????
  2. public class Singleton{
  3. private static Singleton instance = new Singleton();
  4. private Singleton(){
  5. }
  6. public static Singleton getInstance(){
  7. return instance;
  8. }
  9. }

懒汉式 - 类一加载就创建对象

  1. public class Singleton{
  2. private static Singleton instance = null;
  3. private Singleton(){
  4. }
  5. public static Singleton getInstance(){
  6. if(instance == null){
  7. return new Singleton();
  8. }
  9. return instance;
  10. }
  11. }

线程安全的双检锁模式

  1. public class Singleton {
  2. //禁止指令重排序
  3. //保证线程之间可见性
  4. private static volatile Singleton instance = null;
  5. private SingletonDemo() {
  6. }
  7. public static Singleton getInstance() {
  8. if (instance == null) { //提高性能
  9. synchronized (Singleton.class) {
  10. if (instance == null) {
  11. instance = new SingletonDemo();
  12. }
  13. }
  14. }
  15. return instance;
  16. }