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

    单例模式的五种实现写法:懒汉、饿汉、双重检验锁、静态内部类、枚举。线程安全的实现方式

      懒汉式:        

        public class Singleton {

            private static Singleton instatnce;

            private Singleton(){}

            public static synchronized Singleton getInstance(){
              if(instatnce == null)
                instatnce=new Singleton();
              return instatnce;
             }

        }

      双重检验锁: 

        public class Singleton {  

            private static Singleton instatnce;


            private Singleton(){}

            public static Singleton getInstance(){
              if(instatnce == null){
                synchronized(Singleton.class){
                  if(instatnce == null)
                    instatnce=new Singleton();
                }
              }
              return instatnce;
            }

        }

      饿汉式:

        

        public class Singleton {

          private static Singleton instatnce=new Singleton();

          private Singleton(){}

          public static Singleton getInstance(){
            return instatnce;
          }

        }

      静态内部类:

        

        public class Singleton {

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

          private Singleton(){}

          public static final Singleton getInstance(){
            return SingletonHolder.INSTANCE;
          }

        }

      枚举:

        

        public enum EasySingleton {

          INSTANCE;

        }

  • 相关阅读:
    管理者的四种不同授权风格
    centos7 未启用swap导致内存使用率过高。
    Dynamically create a div element with JavaScript/jQuery
    sql server: Parent/Child hierarchy tree view
    视频编解码系列(一)压缩编码基础常识
    mac 常用终端命令
    Linux下安装Python3.6.8
    SQL特殊字符转义
    Ehcache缓存监控
    指标管理体系设计
  • 原文地址:https://www.cnblogs.com/rookie404/p/5792414.html
Copyright © 2011-2022 走看看