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

    1、单例设计模式之饿汉式

     1 public class Singleton {
     2 
     3     // 将自身实例化对象设置为一个属性,并用static、final修饰
     4     private static final Singleton instance = new Singleton();
     5     
     6     // 构造方法私有化
     7     private Singleton() {}
     8     
     9     // 静态方法返回该实例
    10     public static Singleton getInstance() {
    11         return instance;
    12     }
    13 }

    2、单例设计模式之懒汉式

     1 public class Singleton {
     2 
     3     // 将自身实例化对象设置为一个属性,并用static修饰
     4     private static Singleton instance;
     5     
     6     // 构造方法私有化
     7     private Singleton() {}
     8     
     9     // 静态方法返回该实例
    10     public static Singleton getInstance() {
    11         // 第一次检查instance是否被实例化出来,如果没有进入if块
    12         if(instance == null) {
    13             synchronized (Singleton.class) {
    14                 // 某个线程取得了类锁,实例化对象前第二次检查instance是否已经被实例化出来,如果没有,才最终实例出对象
    15                 if (instance == null) {
    16                     instance = new Singleton();
    17                 }
    18             }
    19         }
    20         return instance;
    21     }
    22 }

    完结。。。

  • 相关阅读:
    053-98
    053-672
    053-675
    1031 Hello World for U (20分)
    1065 A+B and C (64bit) (20分)
    1012 The Best Rank (25分)
    1015 Reversible Primes (20分)
    1013 Battle Over Cities (25分)
    1011 World Cup Betting (20分)
    1004 Counting Leaves (30分)
  • 原文地址:https://www.cnblogs.com/sheep9527/p/14503174.html
Copyright © 2011-2022 走看看