Friday, June 7, 2013

Observer Design Patterns in c#

*The Observer pattern in which registered investors are notified every time a stock changes value.

class Program
    {
        static void Main(string[] args)
        {
            IBM ibm = new IBM("IBM", 1202.00);
            ibm.Attach(new Investor("Sorros"));
            ibm.Attach(new Investor("Berkshire"));

            ibm.Price = 120.00;
            ibm.Price = 121.00;
            ibm.Price = 120.44;

            Console.ReadKey();
        }
    }

    interface IInvestor
    {
        void Update(Stock stock);
    }
    abstract class Stock
    {
        //An abstract class cannot be instantiated. 
        //The purpose of an abstract class is to provide "a common definition of a base class" that multiple derived classes can share. 
        private string _symbol;
        private double _price;
        private List<IInvestor> _investors = new List<IInvestor>();

        public Stock(string symbol, double price)
        {
            _symbol = symbol;
            _price = price;
        }
        public void Attach(IInvestor investor)
        {
            _investors.Add(investor);
        }
        public void Detach(IInvestor investor)
        {
            _investors.Remove(investor);
        }
        public void Notity()
        {
            foreach (IInvestor investor in _investors)
            {
                investor.Update(this);
            }
        }
        public double Price
        {
            get { return _price; }
            set
            {
                if (_price != value)
                {
                    _price = value;
                    Notity();
                }
            }
        }
        public string Symbol
        {
            get { return _symbol; }
        }
    }

    class IBM : Stock
    {
        public IBM(string symbol, double price) : base(symbol, price) { }
    }
    class Investor : IInvestor
    {
        private string _name;
        private Stock _stock;

        public Investor(string name)
        {
            this._name = name;
        }

        internal Stock Stock
        {
            get { return _stock; }
            set { _stock = value; }
        }

        public void Update(Stock stock)
        {
            Console.WriteLine("Notified {0} of {1}'s " + "Change to {2:C}", _name, stock.Symbol, stock.Price);
        }
    }

No comments:

Post a Comment