• 我喜欢的两种单例写法


    1,第一种:

     1 package ToolPackage
     2 {
     3  /**
     4   * 提示
     5   * @author tqr <br />
     6   * 创建时间:2014-11-7 下午6:27:10
     7   */
     8  public class Tip
     9  {
    10   private static  var instanceB:Boolean=true;  
    11   private static var instance:Tip;
    12   
    13   public function Tip()
    14   {
    15    if (instanceB) {  
    16     throw new Error("该类为单例,只能用getInstance()来获取实例");  
    17    }  
    18   }
    19   
    20   public static function getInstance():Tip{
    21    if (!instance) {  
    22     instanceB = false;  
    23     instance = new Tip();  
    24     instanceB = true;  
    25    }  
    26    return instance;  
    27   }
    28   
    29  }
    30 }


    2,第二种:

     1 package ToolPackage
     2 {
     3  /**
     4   * 提示
     5   * @author tqr <br />
     6   * 创建时间:2014-11-7 下午6:27:10
     7   */
     8  public class Tip
     9  {
    10   private static var instance:Tip = new Tip();
    11   
    12   public function Tip()
    13   {
    14    if (instance) {  
    15     throw new Error("该类为单例,只能用getInstance()来获取实例");  
    16    }  
    17   }
    18   
    19   public static function getInstance():Tip{
    20    return instance;  
    21   }
    22   
    23  }
    24 }
  • 相关阅读:
    程序是怎样跑起来的 第三章
    C#4.5-4.7学习总结
    第二周学习总结
    程序是如何跑起来的 第二章
    第一章读后感
    师生关系读后感
    C#学习总结
    我与计算机
    读《程序怎样跑起来》第一章有感
    读师生关系有感
  • 原文地址:https://www.cnblogs.com/shuishenwuyu/p/4082018.html
Copyright © 2020-2023  润新知