Friday, June 7, 2013

Observer Design Patterns in c#

Observer: Allows a single object to notify many dependent objects that its state has changed.

class Program
    {
        static void Main(string[] args)
        {
            DummyProduct product = new DummyProduct();

            // We have four shops wanting to keep updated price set by product owner
            Shop shop1 = new Shop("Shop 1");
            Shop shop2 = new Shop("Shop 2");

            Shop shop3 = new Shop("Shop 3");
            Shop shop4 = new Shop("Shop 4");

            //Lets use WAY_1 for first two shops
            product.Attach(shop1);
            product.Attach(shop2);

            //Lets use WAY_2 for other two shops
            product.Attach2(shop3);
            product.Attach2(shop4);

            //Now lets try changing the products price, this should update the shops automatically
            product.ChangePrice(23.0f);

            //Now shop2 and shop 4 are not interested in new prices so they unsubscribe
            product.Detach(shop2);
            product.Detach2(shop4);

            //Now lets try changing the products price again
            product.ChangePrice(26.0f);

            Console.Read();
        }
    }
    interface IObserver
    {
        void Update(float price);
    }
    class Shop : IObserver
    {
        string name;
        float price = 0.0f;

        public Shop(string name)
        {
            this.name = name;
        }

        #region IObserver Members

        public void Update(float price)
        {
            this.price = price;
            Console.WriteLine(@"Price at {0} is now {1}", name, price);
        }

        #endregion
    }
    abstract class ASubject
    {
        ArrayList list = new ArrayList();

        public delegate void StatusUpdate(float price);
        public event StatusUpdate OnStatusUpdate = null;

        public void Attach(Shop product)
        {
            list.Add(product);
        }
        public void Detach(Shop product)
        {
            list.Remove(product);
        }
        public void Attach2(Shop product)
        {
            OnStatusUpdate += new StatusUpdate(product.Update);
        }
        public void Detach2(Shop product)
        {
            OnStatusUpdate -= new StatusUpdate(product.Update);
        }
        public void Notify(float price)
        {
            foreach (Shop p in list)
            {
                p.Update(price);
            }
            if (OnStatusUpdate != null)
                OnStatusUpdate(price);
        }

    }
    class DummyProduct : ASubject
    {
        public void ChangePrice(float price)
        {
            Notify(price);
        }

    }

No comments:

Post a Comment