Loading

23种设计模式之单例模式(Singleton)

单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。

public class SingleTon  
{  
    private static SingleTon singleTon = null;//声明并初始化为null  
    public SingleTon()  
    {  
  
    }  
  
    /// <summary>  
    /// 创建SingleTon对象  
    /// </summary>  
    /// <returns></returns>  
    public static SingleTon GetInstance()  
    {  
        if (singleTon == null)  
        {  
            singleTon = new SingleTon();  
        }  
        return singleTon;  
    }  
  
    /// <summary>  
    /// 调用测试方法  
    /// </summary>  
    public void Print()  
    {  
        Console.WriteLine("打印吧");  
    }  
}  
class Program  
{  
    static void Main(string[] args)  
    {  
        //单例模式  
        SingleTon singleTon1 = SingleTon.GetInstance();  
        SingleTon singleTon2 = SingleTon.GetInstance();  
        SingleTon singleTon3 = SingleTon.GetInstance();  
        SingleTon singleTon4 = SingleTon.GetInstance();  
        SingleTon singleTon5 = SingleTon.GetInstance();  
  
        if (singleTon1 == singleTon2 && singleTon2 == singleTon3 && singleTon3 == singleTon4 && singleTon4 == singleTon5)  
        {  
            Console.WriteLine("相等");  
            singleTon1.Print();  
        }  
    }  
}  

 

posted @ 2017-04-10 15:39  guwei4037  阅读(161)  评论(0编辑  收藏  举报