观察者模式(C#实现 + eventhandler)

namespace ObserverPattern
{
    public interface ISubject
    {
        event EventHandler NotifyHandler; 
    }

    public class CstEventArg : EventArgs
    {
        public string Name { get; set; }
    }

    public class News : ISubject
    {
        public event EventHandler NotifyHandler;

        public void NotifyChanges(EventArgs e)
        {
            if (NotifyHandler != null)
            {
                NotifyHandler(null, e);
            }
        }
    }

    public class CommonOne
    {
        public CommonOne(ISubject subject)
        {
            subject.NotifyHandler += ShowInConsole;
        }

        public void ShowInConsole(object sender, EventArgs e)
        {
            Console.WriteLine("show in console " + (e as CstEventArg).Name);
        }
    }

    public class CommonTwo
    {
        public CommonTwo(ISubject subject)
        {
            subject.NotifyHandler += ShowInConsole;
        }

        public void ShowInConsole(object sender, EventArgs e)
        {
            Console.WriteLine("show in WPF " + (e as CstEventArg).Name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            News news = new News();
            CommonOne cp1 = new CommonOne(news);
            CommonTwo cp2 = new CommonTwo(news);

            news.NotifyChanges(new CstEventArg() { Name = "abc" });
            Console.ReadLine();
        }
    }
}
posted @ 2012-10-18 14:06  webglcn  阅读(499)  评论(0编辑  收藏  举报