オブザーバーモード(C#インプリメンテーション+eventhandler)

4354 ワード

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();

        }

    }

}