码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-05-12 05:49:03      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

(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.

大概结构来描述就如下:

bubuko.com,布布扣

 

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

bubuko.com,布布扣

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; } }
bubuko.com,布布扣

运行代码看一下结果:

bubuko.com,布布扣
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();
    }
}
bubuko.com,布布扣

bubuko.com,布布扣

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

谢谢大家!

小故事学设计模式之Observer : (三) 老婆帮忙订机票,布布扣,bubuko.com

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

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/yongyong/p/3721137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!