ma.citi

A Coder's Blog

An example of use of the observer design pattern in c sharp

This is my implementation of the observer design pattern using C#. I created a simple example using an event and a delegate.

The TicketSeller object (that has the purpose to sell tickets) has an event named OnSale. You can subscribe to this event in order to be notified when the tickets are on sale.

     public delegate void SaleStatusHandler();

    public enum SaleStatus
    {
        Closed,
        Announced,
        OnSale,
        Expired
    }

    public class TicketSeller
    {
        public event SaleStatusHandler OnSale;

        private SaleStatus _saleStatus;
        public SaleStatus SaleStatus
        {
            get {

                return _saleStatus;
            }

            set
            {
                _saleStatus = value;

                if (_saleStatus == SaleStatus.OnSale && OnSale != null)
                    OnSale();
            }

        }
    }

How to subscribe? (lambda syntax)

	TicketSeller t = new TicketSeller();

        //lambda subscription
    t.OnSale += () => Console.WriteLine("Tickets are on sale now");

or using other different syntaxes

    //classic subscription
    t.OnSale += TicketsAreOnSale;

    //or..
    t.OnSale += new SaleStatusHandler(TicketsAreOnSale);
			
			
	public static void TicketsAreOnSale()
	{
		Console.WriteLine("------ tickets are on sale ------");
	}

How to test it? As soon as the status of the tickets goes on sale you will be notified..

	t.SaleStatus = SaleStatus.OnSale;
	
	Console.ReadLine();