您的位置:首页 > 其它

接口(猫,鼠,人联动事类) 观察者模式

2008-10-24 11:56 204 查看
using System;

using System.Collections.Generic;

using System.Text;

using System.Collections;

namespace Observer

{



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

{

/**//// <summary>

/// 应用程序的主入口点。

/// </summary>

[STAThread]

static void Main(string[] args)

{

Cat cat = new Cat();

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

Master master = new Master(cat);

cat.Cry();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: