关闭

Two Interview questions! about event and Observer mode

671人阅读 评论(0) 收藏 举报

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

        }

    }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:336589次
    • 积分:5868
    • 等级:
    • 排名:第4520名
    • 原创:248篇
    • 转载:19篇
    • 译文:0篇
    • 评论:38条
    最新评论