C#設計模式系列 1 —-Observer 觀察者模式 之 牛頓童鞋 的成績

來源:互聯網
上載者:User

   1.理論定義

        觀察者模式 描述了 一種 一對多的關係。 當某一對象的狀態發生改變時,其他對象會得到 改變的通知。並作出相應的反應。

   2.應用舉例

          需求描述:牛頓同學的期末考試成績(Score)出來了,各科老師都想知道自己的 學生 成績情況!

                        語文老師(TeacherChinese)只關心  牛頓的語文(Chinese)成績.

                        英語老師(TeacherEnglish)只關心  牛頓的英語(English)成績.

                        數學老師(TeacherMathematics)只關心  牛頓的數學(Mathematics)成績.

                        班主任想關心(TeacherTeacherHead)    牛頓的各科成績和總成績(TotalScore).

                        成績出來後,各科老師都得到通知(Notify).

   3.具體編碼

          1.新增學生資訊類,裡面只有一個Name屬性。

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Com.Design.Gof.Observer{    /// <summary>    /// 學生資訊類    /// </summary>    public class Student    {        /// <summary>        /// 姓名        /// </summary>        public string Name { get; set; }    }}

   2.成績單(Score)

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Com.Design.Gof.Observer{    public delegate void NotifyEventHandler(Score score);     public class Score    {        public Score() { }        //事件聲明        public NotifyEventHandler NotifyEvent=null;        /// <summary>        /// 調用入口        /// </summary>        public void Notify() {            OnNotifyChange();        }      /// <summary>      ///通知事件      /// </summary>        private void OnNotifyChange() {            if (NotifyEvent != null) {                NotifyEvent(this);            }        }        /// <summary>        /// 數學成績        /// </summary>        public float Mathematics { get; set; }        /// <summary>        /// 英語成績        /// </summary>        public float English { get; set; }        /// <summary>        /// 語文成績        /// </summary>        public float Chinese { get; set; }        /// <summary>        /// 三科總成績        /// </summary>        public float TotalScore {            get {                return Mathematics+English+Chinese;           }        }        /// <summary>        /// 學生基本資料        /// </summary>        public Student student { get; set; }    }}

3.語文老師

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Com.Design.Gof.Observer{    /// <summary>    /// 語文老師    /// </summary>    public class TeacherChinese    {        public void Receive(Score score) {            Console.WriteLine("我是語文老師,我只關心"+score.student.Name+"的語文成績:"+score.Chinese+"分");        }    }}

4.英語老師

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Com.Design.Gof.Observer{    /// <summary>    /// 英語老師    /// </summary>    public class TeacherEnglish    {        public void Receive(Score score) {            Console.WriteLine("我是英語老師,我只關心" + score.student.Name + "的英語成績:" + score.English + "分");        }    }}

5.數學老師

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Com.Design.Gof.Observer{    /// <summary>    /// 數學老師    /// </summary>    public class TeacherMathematics    {        public void Receive(Score score) {            Console.WriteLine("我是數學老師,我只關心" + score.student.Name + "的數學成績:" + score.Mathematics + "分");        }    }}

6.班主任

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Com.Design.Gof.Observer{    /// <summary>    /// 班主任    /// </summary>    public class TeacherTeacherHead    {        public void Receive(Score score) {            string name=score.student.Name;            Console.WriteLine("我是班主任,我要關心 " + name + " 的各科成績和總成績");                      Console.WriteLine(name + "的 語文 成績: " + score.Chinese + " 分");            Console.WriteLine(name + "的 英語 成績: " + score.English + " 分");            Console.WriteLine(name + "的 數學 成績: " + score.Mathematics + " 分");            Console.WriteLine(name + "的 總 成績: " + score.TotalScore + " 分");        }    }}

7.下面是主函數調用

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Com.Design.Gof.Observer;namespace Com.Design.Gof.Test{    class Program    {        static void Main(string[] args)        {            #region Observer            /*牛頓同學的成績單*/            Score score = new Score {                Chinese = 60,                Mathematics = 100,                English = 90,                student = new Student { Name = "牛頓" }            };            TeacherChinese teacherChinese = new TeacherChinese();   //語文老師            TeacherEnglish teacherEnglish = new TeacherEnglish();//英語老師            TeacherMathematics teacherMathematics = new TeacherMathematics();//數學老師            TeacherTeacherHead teacherTeacherHead = new TeacherTeacherHead();//班主任            //牛頓成績單出來了,老師都想知道這個結果。            score.NotifyEvent += new NotifyEventHandler(teacherChinese.Receive);            score.NotifyEvent += new NotifyEventHandler(teacherEnglish.Receive);            score.NotifyEvent += new NotifyEventHandler(teacherMathematics.Receive);            score.NotifyEvent += new NotifyEventHandler(teacherTeacherHead.Receive);            //向 各 學科  老師發送 有針對性的,感興趣的  成績            score.Notify();            #endregion            Console.ReadKey();        }    }}

8.運行結果

  

9.總結

  應用C#語言提供的事件和通知,可以讓觀察者模式更加優雅的實現。事件的 +=操作,實在是讓人So happy。

  附件裡麵包括了程式源碼。

這裡是附件下載(Download)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.