• 设计模式01 单例模式


    单例模式(Singleton)定义:一个类只能有一个实例,且该类能自行创建这个实例的模式。

    单例模式有三个特点:

    1、单例类只有1个实例对象。

    2、该单例对象必须由单例类自己创建。

    3、单例类对外提供一个访问该唯一实例的全局访问点。

    懒加载实现:

     1 public class LazySingleton {
     2 
     3     private static volatile LazySingleton lazySingleton = null;
     4 
     5     private LazySingleton() {
     6 
     7     }
     8 
     9     public static synchronized LazySingleton getInstance() {
    10         if (lazySingleton == null) {
    11             lazySingleton = new LazySingleton();
    12         }
    13         return lazySingleton;
    14     }
    15 }

    饥饿式实现:

     1 public class HungrySingleton {
     2 
     3     private static final HungrySingleton instance = new HungrySingleton();
     4 
     5     private HungrySingleton() {
     6 
     7     }
     8 
     9     public static HungrySingleton getInstance() {
    10         return instance;
    11     }
    12 }

    调用方式:

     1 public class Client {
     2 
     3     public static void main(String[] args) {
     4         // TODO Auto-generated method stub
     5 
     6         LazySingleton l1 = LazySingleton.getInstance();
     7         LazySingleton l2 = LazySingleton.getInstance();
     8         System.out.println(l1 == l2);
     9 
    10         HungrySingleton h1 = HungrySingleton.getInstance();
    11         HungrySingleton h2 = HungrySingleton.getInstance();
    12         System.out.println(h1 == h2);
    13     }
    14 
    15 }

    执行结果:

    多线程环境下的双重检查机制:

     1 public class MultiThreadSingleton {
     2 
     3     private static volatile MultiThreadSingleton multiThreadsSingleton = null;
     4 
     5     private MultiThreadSingleton() {
     6         System.out.println("MultiThreadSingleton init");
     7     }
     8 
     9     public static MultiThreadSingleton getInstance() {
    10         if (multiThreadsSingleton == null) {
    11             synchronized (MultiThreadSingleton.class) {
    12                 if (multiThreadsSingleton == null) {
    13                     multiThreadsSingleton = new MultiThreadSingleton();
    14                 }
    15             }
    16         }
    17         return multiThreadsSingleton;
    18     }
    19 
    20     public static void main(String[] args) {
    21         // TODO Auto-generated method stub
    22         for (int i = 0; i < 10; i++) {
    23             new Thread(() -> {
    24                 MultiThreadSingleton.getInstance();
    25             }).start();
    26         }
    27 
    28     }
    29 }
  • 相关阅读:
    TensorFlow入门:debug方法
    Firefox 隐藏提示:正在安装组件,以便播放此页面的音频或视频
    CentOS 6.5挂载windows NTFS硬盘
    Linux中执行shell脚本
    CentOS opera 浏览器
    CentOS 更新为网易yum源
    Centos下替换yum源为阿里云源
    CentOS常用基础命令大全
    Linux CentOS删除或重命名文件夹和文件的办法
    给Centos7装上Chromium
  • 原文地址:https://www.cnblogs.com/asenyang/p/12111014.html
Copyright © 2020-2023  润新知