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

    单例模式

    什么是单例模式?

     单例保证一个对象JVM中只能有一个实例,常见单例 懒汉式、饿汉式

     什么是懒汉式,就是需要的才会去实例化,线程不安全。

     什么是饿汉式,就是当class文件被加载的时候,初始化,天生线程安全。

    单例写法

    懒汉式代码

     

    class SingletonTest {

         public static void main(String[] args) {

             Singleton sl1 = Singleton.getSingleton();

             Singleton sl2 = Singleton.getSingleton();

             System.out.println(sl1 == sl2);

         }

    }

     

    public class Singleton {

         // 当需要的才会被实例化

         private static Singleton singleton;

         private Singleton() {

         }

         synchronized public static Singleton getSingleton() {

             if (singleton == null) {

                  singleton = new Singleton();

             }

             return singleton;

         }

    }

     

    双重检验锁

         // 懒汉式 第二种写法 效率高    双重检验锁

         static public Singleton getSingleton2() {

     

             if (singleton == null) { // 第一步检验锁

                  synchronized (Singleton.class) {  // 第二步检验锁

                       if (singleton == null) {

                           singleton = new Singleton();

                       }

     

                  }

             }

     

             return singleton;

         }

     

    饿汉式代码

    class SingletonTest1 {

           public static void main(String[] args) {

                  Singleton1 sl1 = Singleton1.getSingleton();

                  Singleton1 sl2 = Singleton1.getSingleton();

                  System.out.println((sl1 == sl2)+"-");

           }

    }

    public class Singleton1 {

           //class 文件被加载初始化

           private static Singleton1 singleton = new Singleton1();

           private Singleton1() {

           }

           public static Singleton1 getSingleton() {

                  return singleton;

           }

     

    }

  • 相关阅读:
    使用百度网盘配置私有Git服务
    Linked dylibs built for GC-only but object files built for retain/release for architecture x86_64
    我的博客搬家啦!!!
    今日头条核心业务(高级)开发工程师,直接推给部门经理,HC很多,感兴趣的可以一起聊聊。
    学习Python的三种境界
    拿到阿里,网易游戏,腾讯,smartx的offer的过程
    关于计算机网络一些问题的思考
    网易游戏面试经验(三)
    网易游戏面试经验(二)
    网易游戏面试经验(一)
  • 原文地址:https://www.cnblogs.com/super-admin/p/9728849.html
Copyright © 2011-2022 走看看