首页 > 代码库 > 小故事学设计模式之Observer : (三) 老婆帮忙订机票

小故事学设计模式之Observer : (三) 老婆帮忙订机票

(IT的事就是过场多,过场多了就容易忘,所以我们不妨看一个记一个,这也是一个办法,顺便还能跟同行们交流一下) 

要和老婆一起回老家了, 成都离我们安徽太远, 两个人飞一下过去就要花掉近三千块, 于是我们决定找找有没有更便宜的机票,

"你帮我找找吧, 如果找到的话,跟我说一下",我说道.

"行!"老婆记住了这事.

很快我得到通知, 南航有更便宜的, 580块.

这是一个简单的observer模式.

什么是observer? 其定义如下:

The Observer Patern defines a one-to-many dependency betwen objects so that when one object changes state, all its dependents are notified and updated automatically.

大概结构来描述就如下:

345

 

其中Neo(就是我以前在IT混日子的马甲拉)是继承于TicketBuyer这个抽象类的, 为什么这里要加一个抽象类,因为老婆表兄妹多, 都有可能找她订票, 所以要把这些表兄妹的行为抽象到一个公共的抽象类上.


using
System; using System.Collections.Generic; public abstract class TicketBuyer { public int TicketPrice; public string Airline; } public class Neo: TicketBuyer { private int _ticketPrice; private string _airline; public int TicketPrice { get {return _ticketPrice;} set {_ticketPrice = value;} } public string Airline { get{return _airline;} set{_airline = value;} } } public class FeiFei { private string _airline; private int _ticketPrice; IList<TicketBuyer> _ticketBuyers; public FeiFei() { _ticketBuyers = new List<TicketBuyer>(); } public void AddTicketBuyer(TicketBuyer t) { _ticketBuyers.Add(t); } public void DeleteTicketBuyer(TicketBuyer t) { _ticketBuyers.Remove(t); } public void NotifyTicketInformation() { SearchTicket(); foreach(TicketBuyer t in _ticketBuyers) { t.Airline = _airline; t.TicketPrice = _ticketPrice; } } private void SearchTicket() { _airline = "China Southern"; _ticketPrice = 580; } }

运行代码看一下结果:

public class Test
{
    public static void Main()
    {
        TicketBuyer n = new Neo();
        FeiFei f = new FeiFei();
        f.AddTicketBuyer(n);
        f.NotifyTicketInformation();
        Console.WriteLine("Airline:" + n.Airline + ", price:" + n.TicketPrice);
        Console.Read();
    }
}

image

好了,以上是个人对Observer模式的理解,如有不正确的地方,希望同行能帮我纠正。

谢谢大家!