訂票 By Queue(敬請糾正)

  • 446
  • 0
  • C#
  • 2013-07-29

摘要:訂票 By Queue(敬請糾正)

筆者使用了Queue想模擬簡易訂票的流程(未實作過正式的線上訂票) ,

 

可是感覺自己有些地方觀念還不清楚 , 

 

若有經驗的大大希望能糾正我一下 , 

 

如何修改會比較好 ? 另外訂票完成之後的訊息怎樣傳達給使用者會比較好?

 


 public class TroopQueue
    {

        private static readonly Queue CustomerQueue = new Queue();



        public TroopQueue() { }

        
        //新增顧客
        public void AddCustomer(Customer cust)
        {

            lock (this)
            {
                CustomerQueue.Enqueue(cust);
            }
        }

        //取得顧客
        public Customer GetCustomer()
        {

            Customer cust = null;

            lock (this)
            {
                cust = CustomerQueue.Dequeue();
            }

            return cust;
        }

        //是否還有顧客
        public bool IsCustAvailable
        {

            get
            {
                return CustomerQueue.Count > 0;
            }
        }



    }

 


public class ProcessQueue
{
    private  TroopQueue queueManager;

    private ProcessQueue() { }



    protected ProcessQueue(TroopQueue tq)
    {
        queueManager = tq;
    }

    public static void Start(TroopQueue tq)
    {
        new Thread(new ProcessQueue(tq).Run).Start();
    }


    private void Run(){

      while (true)
      {
         if (queueManager.IsCustAvailable)
         {
            Customer cust =  queueManager.GetCustomer();
            //訂票(cust) 執行訂票程序,存取service等
         }
         Thread.Sleep(new Random().Next(20));
      }
    }


}

 


public class Customer
{

    public string name {get;set;}
    public string ip {get;set;}

    private Customer(){
    
        
    }

    public Customer(string name, string ip) {
        this.name = name;
        this.ip = ip;
    }

}

 


顧客訂票頁面
 
protected void Page_Load(object sender, EventArgs e)
    {


        TroopQueue tq = new TroopQueue();
       
        ProcessQueue.Start(tq);

        Customer cust = new Customer("Customer " , "192.168.0.1");
        tq.AddCustomer(cust);
     Response.Write(string.Format("Added Customer {0}", cust.ip));

}