1. 程式人生 > >觀察者模式-貓捉老鼠(委託與事件)

觀察者模式-貓捉老鼠(委託與事件)

貓捉老鼠是一個典型的觀察者模式的實現案例,在其中加入委託與事件的程式實現,將會提高程式碼的一個可讀性,其下是程式碼實現:

建立一個Cat類:

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 貓捉老鼠
{
    /// <summary>
    /// 定義一個貓類
    /// </summary>
    class Cat
    {
        public string name;
        public string color;

        public  Cat(string name, string color)
        {
            this.name = name;
            this.color = color;
        }
        /// <summary>
        /// 定義貓來了狀態
        /// </summary>
        public void CatComing()
        {
            Console.WriteLine(color+"這個"+name+"來了,喵喵貓~~~");
            if (CatCome != null)

                CatCome();

        }
        /// <summary>
        /// 定義一個事件
        /// </summary>
        public event Action CatCome;

    }
    
}

建立一個mouse類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 貓捉老鼠
{
    /// <summary>
    /// 定義一個老鼠類
    /// </summary>
    class mouse
    {
        public string name;
        public string color;

        public mouse(string name, string color,Cat cat)
        {
            this.name = name;
            this.color = color;
            cat.CatCome += this.RunAway;//將貓自身的方法註冊進老鼠中
        }

        public void RunAway()
        {
            Console.WriteLine(color+"這個"+name+"的跑了~~~");
        }
    }
}
在program類中實現:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 貓捉老鼠
{
    class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat("老虎貓", "藍色");           
            mouse mouse1=new mouse("米老鼠","灰色",cat);
          //  cat.CatCome += mouse1.RunAway;
            mouse mouse2 = new mouse("唐老鴨", "黑色",cat);
         //   cat.CatCome += mouse2.RunAway;
            mouse mouse3 = new mouse("任意貓", "任意色",cat);
          //  cat.CatCome += mouse3.RunAway;
           cat.CatComing();//貓的狀態發生改變
            Console.ReadKey();
        }
    }
}

完成整個案例的開發。