设计模式-单例模式(一)

85 阅读1分钟

为什么要使用单例模式

  1. 如果频繁创建一个很大的对象,这对cpu,内存,时间都产生不小的开销。

  2. 减少new过程,将减少GC压力,缩短GC停顿时间。

  3. 对于线程池,缓存,日志对象,这类对象只能有一个,多个对象会造成数据不一致问题。

单例模式的实现需要三个必要的条件

  1. 单例类的构造函数必须是私有的,这样才能将类的创建权控制在类的内部,从而使得类的外部不能创建类的实例。
  2. 单例类通过一个私有的静态变量来存储其唯一实例。
  3. 单例类通过提供一个公开的静态方法,使得外部使用者可以访问类的唯一实例。

写个单例模式

/**
 * @version 1.0
 * @desc 饿汉式单例设计模式-线程不安全
 * @since 1.0
 */
public class Single {
    private static Single instance = new Single();

    private Single() {
    }

    public static Single getInstance() {
        return instance;
    }

    public void method2() {
        System.out.println("Single的mehtod2方法");
    }

    public void method3() {
        System.out.println("Single的method3方法");
    }
}
/**
 * 懒汉是单例模式
 */
class SingleLazy {

    private static SingleLazy instance = null;

    private SingleLazy() {
    }

    public static synchronized SingleLazy getInstance() {
        if (instance == null) {
            return instance = new SingleLazy();
        } else {
            return instance;
        }
    }
}

适用场景

1.需要频繁实例化然后销毁的对象。

2.创建对象时耗时过多或者耗资源过多,但又经常用到的对象。

3.频繁访问数据库或文件的对象。

创建单例方式

  1. 饿汉

  2. 懒汉

  3. 静态内部类

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    private Singleton() {
    }

    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
  1. 枚举
public enum SingletonEnum {
    INSTANCE;
    public void whateverMethod() {
    }
}