Re: [問題] 關於取代polling的問題

作者: StupidGaGa (笨嘎嘎)   2015-02-06 11:21:38
※ 引述《ching99 (只要食物不要胖)》之銘言:
: 我用生活化的假設好了
: 假如我有兩個class 一個是 "媽媽炒菜"
: 一個是"兒子看電視" 然後有一支電話
: 情境是這樣 媽媽知道外婆會打電話來
: 所以一邊炒菜一邊不停的去詢問兒子說"電話來了沒"
: 然後直到兒子接到電話然後
: 確認是外婆而不是隔壁老王才通知媽媽說
: "媽~外婆的電話"
: 這是一般polling的機制
: 但是 我想要這個兒子主動點
: 外婆打過來就直接通知媽媽而不是媽媽去問兒子
: 請問我要用什麼方法?
: public void MomCook()
: {
: answerPhone();
: }
: bool answerPhone()
: {
: if( GrandMon())
: return true;
: return false;
: }
你的class跟你的敘述不合,兩種方式讓你自己選
一、正常用法
1. mother class
public void Mother()
{
public void Cook()
{
Console.WriteLine("媽媽煮菜");
}
public void SayHello()
{
Console.WriteLine("媽媽:Hello");
}
}
2. son class
public void Son()
{
public event EventHandler GotPhoneCall;
public void WatchTV()
{
Console.WriteLien("兒子看電視");
}
public void GetPhoneCall()
{
Console.WriteLine("兒子接到電話");
if (this.GotPhoneCall != null)
{
this.GotPhoneCall(this, null);
}
}
}
3. phone class
public void Phone()
{
event EventHandler Rang;
public void Ring()
{
Console.WriteLine("電話響了");
if(this.Rang != null)
{
this.Rang(this, null);
}
}
}
4. client
Phone phone = new Phone();
Son son = new Son();
Mother mother = new Mother();
phone.Rang += new EventHandler((s, e) => son.GetPhoneCall());
son.GotPhoneCall += new EventHandler((s, e) => mother.SayHello());
phone.Ring();
二、
懶得打了,我用說的,
將電話的事件註冊到兒子建構式,
將兒子事件註冊到媽媽建構式,
呼叫就直接這樣寫
Mother mother = new Mother();
mother.son.phone.Ring();
效果一樣,但是意義不一樣,
要注意這點,
然後接下來應該就會有人找碴說我誤導新手,
所以第二段不打了,可以當作練習自己打出來看看。
作者: ching99 (只要食物不要胖)   2015-02-26 12:14:00
謝謝大大

Links booklink

Contact Us: admin [ a t ] ucptt.com