software-mariodiana
3/10/2016 - 7:47 PM

A simple example of the Observer pattern.

A simple example of the Observer pattern.

using System;
using System.Collections.Generic;
using System.Text;

namespace ObserverExample
{
    class Program
    {
        static void Main(string[] args)
        {
            NewsBuff buff = new NewsBuff();
            TownCrier crier = new TownCrier();
            // Only 1 buff will subscribe, but multiple could.
            buff.Subscribe(crier);
            Console.WriteLine("Adding news item...");
            crier.Add("Baltimore burns!");
            Console.WriteLine("Adding news item...");
            crier.Add("Cecily Strong too funny for journalists.");
            Console.WriteLine("Adding news item...");
            crier.Add("Mayor DeBlasio no longer stupidest mayor in U.S.");
        }
    }

    class TownCrier
    {
        private List<string> _news;

        public delegate void NotifyHandler(Object sender, ItemWrapper item);

        // Using the "event" keyword means only this class can call the delegate. Other 
        // classes may only subscribe to the (Notify) event.
        public event NotifyHandler Notify;

        public TownCrier()
        {
            _news = new List<string>();
        }

        public void Add(string item)
        {
            _news.Add(item);
            if (Notify != null)
            {
                Notify(this, new ItemWrapper(item));
            }
        }
    }

    class ItemWrapper : EventArgs
    {
        public readonly string Item;

        public ItemWrapper(string anItem)
        {
            Item = anItem;
        }
    }

    class NewsBuff
    {
        // Our handler, which conforms to the TownCrier handler's signature.
        public void NewsHandler(Object sender, ItemWrapper wrapper)
        {
            Console.WriteLine("News item added: " + wrapper.Item);
        }

        // Subscribe to events raised from crier.
        public void Subscribe(TownCrier crier)
        {
            crier.Notify += new TownCrier.NotifyHandler(NewsHandler);
        }
    }
}