zoukankan      html  css  js  c++  java
  • 设计模式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 }
  • 相关阅读:
    阅读笔记《梦断代码》其一
    第一次冲刺(第九天)
    第一次冲刺(第八天)
    第一冲刺阶段(第七天)
    第一冲刺阶段(第六天)
    第一冲刺阶段(第五天)
    MySQL数据库半同步复制
    MySQL事物
    MySQL字符编码
    MySQL用户授权
  • 原文地址:https://www.cnblogs.com/asenyang/p/12111014.html
Copyright © 2011-2022 走看看