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

    //第一种实现方法:类的对象只有一个  懒汉

    public class Singlton1 {
      private static Singlton1 instance;
      //让其外部不能再new 对象
      private Singlton1(){};
      //给外部提供一个方法;得到该类的对象
      public static Singlton1 getInstance(){
        if(instance==null){
          instance = new Singlton1();
        }
        return instance;
      }
    }

    //第二种实现方法:类的对象只有一个  饿汉

    public class Singleton2 {
      private static final Singleton2 instance = new Singleton2();
      private Singleton2(){};
      public static Singleton2 getIntance(){
        return instance;
      }
    }

    //第三种实现方法

    public class Singleton3 {
      private Singleton3(){};
      //静态内部类
      static class InnerSinglton3{
        private static final Singleton3 instance = new Singleton3();
      }
      public static Singleton3 getInstance(){
        return InnerSinglton3.instance;
      }
    }

    //第四种实现方法

    public class Singleton4 {
      private static Singleton4 instance;
      private Singleton4(){};
      public static Singleton4 getInstance(){
        if(instance==null){ //如果不是null,锁都不用锁
          synchronized (Singleton4.class) { //锁模板对象
            if(instance==null){ //加锁的过程中不能确保对象是否已创建,安全起见,再判断一次
              instance = new Singleton4();
            }
          }
        }
        return instance;
      }
    }

  • 相关阅读:
    web端常见兼容性问题整理
    浏览器初始化样式
    html5特效库
    csshack
    进程与线程,并发、并行、异步、多线程
    js复制粘贴事件
    dom range相关
    vue和react在使用上的对比
    ListView往TreView里面拖拽
    ListView添加项目带序列
  • 原文地址:https://www.cnblogs.com/hwgok/p/5352423.html
Copyright © 2011-2022 走看看