zoukankan      html  css  js  c++  java
  • 单例模式

    单例模式(5种)

    单例模式 : 一个只有单一对象的类

    1. 饿汉式 空间性能低
      class A{
      private static final A instance = new A();
      public static A newInstance() {
      return instance;
      }
      private A(){}
      }

    2. 懒汉式 时间性能低
      class B{
      private static B instance = null;
      public static synchronized B newInstance() {
      if (instance == null) instance = new B();
      return instance;
      }
      private B() {}
      }

    3. 融合饿汉式和懒汉式的优点
      class C{
      private static class Holder{
      static final C instance = new C();
      }
      public static C newInstance() {
      return Holder.instance;
      }
      private C() {}
      }

    4. 双重检查锁
      public class Singleton {
      private volatile static Singleton singleton;
      public Singleton() {
      }
      public static Singleton getInstance() {
      if (singleton == null) {
      synchronized (Singleton.class) {
      if (singleton == null) {
      singleton = new Singleton();
      }
      }
      }
      return singleton;
      }
      }

    5. 枚举式
      线程安全,调用效率高,但是不能延时加载,但是可以天然的防止反射和反序列化漏洞**
      public enum SingletonDemo4 {
      //这个枚举对象本身就是单例对象
      INSTANCE;
      //添加自己需要的操作
      public void operation(){
      }、
      }

  • 相关阅读:
    CF1461F
    P7114
    CF576D
    CF1208F
    【2021-05-25】碎片化自有碎片化的办法
    【2021-05-23】人生十三信条
    【2021-05-22】人生十三信条
    【2021-05-21】人做成一件事,第一步往往是戒
    【2021-05-20】确认一个人,也就三秒钟的事情
    【2021-05-19】人生十三信条
  • 原文地址:https://www.cnblogs.com/linanana/p/12107361.html
Copyright © 2011-2022 走看看