beyondjay

 

2008年2月14日

百无聊赖设计模式系列-singleton

今天继续百无聊赖。

许多公司在招人的时候都会要求写一个singleton,我觉得这个本身就蛮可笑的。这个有啥写的,不会的人看5分钟都背出来了。

一般这么写会让你通过。
public sealed class Singleton
 {
     static Singleton instance=null;
 
     Singleton()
     {
     }
 
     public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

但是多线程的时候这个会有多个实例出来的。
所以比较好的还是用下面这个,我把test page和class包括了,还有点注释。我喜欢用page而不是console做test,呵呵。
参考了:
http://www.aspcool.com/lanmu/browse1.asp?ID=1138&bbsuser=csharp
这个作者还有另外一种实现,但是我觉得lazy instantiation还要客户端去单独写代码保证线程同步是有问题的。最好还是在singlton类内部做。

using System;
using System.Threading;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Design_Pattern_Singleton : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Thread thread0 = Thread.CurrentThread;
        thread0.Name = "Thread 0";

        Thread thread1 = new Thread(new ThreadStart(this.DoSomeWork));
        thread1.Name = "Thread 1";

        Thread thread2 = new Thread(new ThreadStart(this.DoSomeWork));
        thread2.Name = "Thread 2";

        Thread thread3 = new Thread(new ThreadStart(this.DoSomeWork));
        thread3.Name = "Thread 3";

        thread1.Start();
        thread2.Start();
        thread3.Start();

        DoSomeWork(); // thread0 do the same work
    }

     public void DoSomeWork()
     {
         MySingleton mySingleton = MySingleton.GetInstance();

         for (int i = 1; i < 5; i++)
         {
             mySingleton.Add();
             Response.Write("Thread" + Thread.CurrentThread.Name.ToString() + "report: the current counter number is " + mySingleton.GetNumber().ToString() + "<br>");
         }

     }

}


public class MySingleton
{
    private MySingleton() { }//it is must for a singleton
    private int totalNum = 0;//for test in test page.
    private static MySingleton mySingleton = new MySingleton();//that means early instantiation, it's safe for multi-thread

    //client get the instance by this method
    public static MySingleton GetInstance()
    {
        return mySingleton;
    }

    // add the value by 1
    public void Add()
    {
        totalNum++;
    }

    //get the count number, for test in test page.
    public int GetNumber()
    {
        return totalNum;
    }
}


 

posted @ 2008-02-14 15:26 Tony Zhou 阅读(25) | 评论 (0)编辑

导航

统计

与我联系

搜索

 

常用链接

留言簿

我参与的团队

我的标签

随笔分类

随笔档案

最新评论

阅读排行榜

评论排行榜