其他分享
首页 > 其他分享> > .NET 观察者模式

.NET 观察者模式

作者:互联网

简单版本实现

1.创建一个控制台项目,名称叫:ObServerPattern.Console

2.新增Sentry,Sergeant类

3.Sentry代码如下:

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

namespace ObServerPattern.Console
{
	/// <summary>
	/// 哨兵
	/// </summary>
	public class Sentry
	{
		// 士官对象集合
		private List<Sergeant> _sergeants = new List<Sergeant>();
		//敌情
		private string _situation;

		public string Situation { get => _situation; set => _situation = value; }

		/// <summary>
		/// 添加需要通知的士官
		/// </summary>
		/// <param name="sergeant"></param>
		public void AddSergeant(Sergeant sergeant)
		{
			_sergeants.Add(sergeant);
		}
		/// <summary>
		/// 通知士官
		/// </summary>
		public void Notify()
		{
			foreach (var _sergeant in _sergeants)
			{
				_sergeant.Update();
			}
		}
	}
}

4.Sergeant代码如下

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

namespace ObServerPattern.Console
{
	/// <summary>
	/// 士官
	/// </summary>
	public class Sergeant
	{
		private string Name;
		private readonly Sentry _sentry;
		public Sergeant(string name, Sentry sentry)
		{
			this._sentry = sentry;
			this.Name = name;
		}
		public void Update()
		{
			System.Console.WriteLine($"{_sentry.Situation}!!!!!{Name} 迅速向连长报告");
		}
	}
}

5.program上端调用代码如下:

program
// See https://aka.ms/new-console-template for more information
using ObServerPattern.Console;

Console.WriteLine("Hello, World!");
//注意哨兵和士官是一对多
//实例化哨兵
Sentry sentry = new();

sentry.Situation = "发现敌情";
//实例化多个士官
Sergeant sergeant1 = new("士官1", sentry);
Sergeant sergeant2 = new("士官2", sentry);
Sergeant sergeant3 = new("士官3", sentry);
sentry.AddSergeant(sergeant1);
sentry.AddSergeant(sergeant2);
sentry.AddSergeant(sergeant3);

sentry.Notify();

标签:sentry,观察者,模式,System,Sergeant,using,NET,士官,public
来源: https://www.cnblogs.com/humblexwang/p/16579034.html