您的位置:首页 > 编程语言 > C#

一道猫和老鼠吵醒主人的笔试题(C#)

2011-07-16 11:15 337 查看
程序設計:貓大叫一聲,所有的老鼠都開始逃跑,主人被驚醒。(C#語言)
要求:
1.要有聯動性,老鼠和主人的行為是被動的。
2.考慮可擴展性,貓的叫聲可能引起其他聯動效應
大部分答案都是使用的事件编程,我这里换了一下思路,使用观察着模式,用接口也实现了,因为考虑到第二个要求,即猫大叫也可能直接导致主人惊醒,所以Man也继承了ICatCatcher接口
源代码如下:
using System;

using System.Collections;

namespace test

{

public interface ICatCatcher

{

void DoSth();

}

public interface ICatSubject

{

void RegesiterCatCatcher(ICatCatcher catCatcher);

void Miao();

}

public interface IRatSubject

{

void RegesiterRatCatcher(IRatCatcher ratCatcher);

void Run();

}

public interface IRatCatcher

{

void Wake();

}

public class Cat:ICatSubject

{

public Cat()

{

}

private ArrayList catcherList = new ArrayList();

public void RegesiterCatCatcher(ICatCatcher catcher)

{

catcherList.Add( catcher );

}

public void Miao()

{

Console.WriteLine( "Miao" );

for(int i=0;i<catcherList.Count;i++)

{

ICatCatcher catCatcher = (ICatCatcher)catcherList;

catCatcher.DoSth();

}

}

[STAThread]

public static void Main()

{

Cat cat = new Cat();

Rat[] rat = new Rat[10];

for( int i=0;i<10;i++)

{

rat = new Rat(cat);

}

Man man = new Man(rat,cat);

cat.Miao();

}

}

public class Rat:ICatCatcher,IRatSubject

{

public Rat(ICatSubject catSub)

{

catSub.RegesiterCatCatcher(this);

}

public void DoSth()

{

Run();

}

private ArrayList ratcherList = new ArrayList();

public void RegesiterRatCatcher(IRatCatcher catcher)

{

ratcherList.Add( catcher );

}

public void Run()

{

Console.WriteLine("Rat Run");

for(int i=0;i<ratcherList.Count;i++)

{

IRatCatcher ratCatcher = (IRatCatcher)ratcherList;

ratCatcher.Wake();

}

}

}

public class Man:ICatCatcher,IRatCatcher

{

public Man(IRatSubject[] ratSub,ICatSubject catSub)

{

for( int i=0 ;i<ratSub.Length;i++)

{

ratSub.RegesiterRatCatcher(this);

}

catSub.RegesiterCatCatcher(this);

}

public void DoSth()

{

Console.WriteLine( "Cat bring on Wake" );

}

public void Wake()

{

Console.WriteLine( "Rats bring on Wake" );

}

}

}

这里如果调试会出现一点点小问题,就是老鼠有很多,每个老鼠的Run都会Wake一下Man,所以感觉是主人被多次惊醒,其实这只是因为计算机总是按照顺序来执行程序的,能够模拟到这种效果应该已经算符合题意了

这里如果调试会出现一点点小问题,就是老鼠有很多,每个老鼠的Run都会Wake一下Man,所以感觉是主人被多次惊醒,其实这只是因为计算机总是按照顺序来执行程序的,能够模拟到这种效果应该已经算符合题意了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: