C#观察者模式

C#观察者模式-----吃鸡实例

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

namespace 观察者模式
{
    //PUBG观察者设计模式
    //定义一个委托当队友发现敌情的时候传递给队友
    public delegate void DelOB(Subject subject, EventArgs e);
    /// 
    /// 被观察者抽象类
    /// 
    public abstract class Subject
    {
        private string _strIntelligence;
        public Subject(string name,string strIntelligence)
        {
            this.Name = name;
            this.StrIntelligence = strIntelligence;
        }
        public event DelOB DelPUBGOB;//当OB队友报出出敌情时候的事件
        /// 
        /// 广播(启动委托事件)
        /// 
        public void PUBGSay()
        {
            //
            DelPUBGOB(this,new EventArgs ());
        }
        
        private string _name;

        public string Name
        {
            get
            {
                return _name;
            }

            set
            {
                _name = value;
            }
        }

        public string StrIntelligence
        {
            get
            {
                return _strIntelligence;
            }

            set
            {
                _strIntelligence = value;
            }
        }
    }
    /// 
    /// 观察者抽象类
    /// 
    public abstract class OBServer
    {
        private string _name;

        public string Name
        {
            get
            {
                return _name;
            }

            set
            {
                _name = value;
            }
        }

        abstract protected void Notified(Subject subject,EventArgs e);
        public OBServer(Subject subject,string name)
        {
            this.Name = name;
            subject.DelPUBGOB += this.Notified;
        }
    }
    /// 
    /// 活着的队友
    /// 
    public class TeammateAlive : OBServer
    {
       
        public TeammateAlive(Subject subject,string name) : base(subject,name)
        {

        }

        protected override void Notified(Subject subject, EventArgs e)
        {
            Console.WriteLine( "{0}:收到",this.Name);
        }
    }
    /// 
    /// 已经死了的队友
    /// 
    public class DieTeammates : Subject
    {
       
        public DieTeammates(string name,string strIntelligence) : base(name,strIntelligence)
        {
           
            Console.WriteLine("{0}:{1}",this.Name,this.StrIntelligence);
        }

       
    }
    class Program
    {
        static void Main(string[] args)
        {
            DieTeammates die = new DieTeammates("JackCC","北偏东75d度发现4个敌人有点慌");
            TeammateAlive team1 = new TeammateAlive(die,"JackDD");
            TeammateAlive team2 = new TeammateAlive(die, "JackFF");
            TeammateAlive team3 = new TeammateAlive(die, "JackGG");
            die.PUBGSay();

        }
    }
}

欢迎指导谢谢 -JackCC

你可能感兴趣的:(C#设计模式)