首页 > 学院 > 开发设计 > 正文

面试习题之设计模式C#观察者模式(猫叫老鼠惊走主人醒)

2019-11-14 15:51:12
字体:
来源:转载
供稿:网友

腾讯云测试|TEST Tencent Cloud

/*

* CatShout.cs

*/

using System;
using System.IO;
using System.Collections;
public interface Observer
{
void Response(); //观察者的响应,如是老鼠见到猫的反映
}
public interface Subject
{
void AimAt(Observer obs); //针对哪些观察者,这里指猫的要扑捉的对象---老鼠
}
public class Mouse : Observer
{
PRivate string name;
public Mouse(string name, Subject subj)
{
this.name = name;
subj.AimAt(this);
}
public void Response()
{
Console.WriteLine(name + " attempt to escape!");
}
}
public class Master : Observer
{
public Master(Subject subj)
{
subj.AimAt(this);
}
public void Response()
{
Console.WriteLine("Host waken!");
}
}
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();
for(int i=0;i<100;i++)
{
Mouse mouse = new Mouse("Mouse: #"+(i+1),cat);
}
Master master = new Master(cat);
cat.Cry();
Console.Read();
}
}

腾讯云测试|TEST Tencent Cloud


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表