diandian82的专栏

Welcome to my blog. Hope you can get what you want.

Two Interview questions! about event and Observer mode

The two solution of interview question.

1. use observer modal

 public interface Observer

{

     void Response();    //the observer’s response

 }

 public class Cat : Subject

 {

private ArrayList observers;

        public Cat()

        {  

            this.observers = new ArrayList();

        }

        public void AimAt(Observer obs)

        {

            this.observers.Add(obs);

        }

        public void Cry()

        {

            Console.WriteLine("Cat cryed!");

            foreach (Observer obs in this.observers)

            {

                obs.Response();

            }

        }

    }

    class MainClass

    {      

        static void Main(string[] args)

        {

            Cat cat = new Cat();

            Mouse mouse1 = new Mouse("mouse1", cat);

            Mouse mouse2 = new Mouse("mouse2", cat);

            Master master = new Master(cat);

            cat.Cry();

        }

    }

 

2 使用事件

public delegate void SubEventHandler();

    public abstract class Subject

    {

        public event SubEventHandler SubEvent;

        protected void FireAway()

        {

            if (this.SubEvent != null)

                this.SubEvent();

        }  

    }

    public class Cat : Subject

    { 

        public void Cry()

        {

            Console.WriteLine("cat cryed.");

            this.FireAway();

        }

    }

    public abstract class Observer

    {

        public Observer(Subject sub)

        {

            sub.SubEvent += new SubEventHandler(Response);

        }

        public abstract void Response();   

    }

    public class Mouse : Observer

    {

        private string name;

        public Mouse(string name, Subject sub) : base(sub)

        {  

            this.name = name;

        }

        public override void Response()

        {

            Console.WriteLine(name + " attempt to escape!");

        }

    }

    public class Master : Observer

    {

        public Master(Subject sub) : base(sub){}

        public override void Response()

        {

            Console.WriteLine("host waken");

        }

    }

    class Class1

    {

        static void Main(string[] args)

        {

            Cat cat = new Cat();

            Mouse mouse1 = new Mouse("mouse1", cat);

            Mouse mouse2 = new Mouse("mouse2", cat);

            Master master = new Master(cat);

            cat.Cry();

        }

    }

阅读更多
个人分类: .Net 其他
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭