簡略的不雅察者形式示例分享。本站提示廣大學習愛好者:(簡略的不雅察者形式示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是簡略的不雅察者形式示例分享正文
using System;
using System.Collections.Generic;
namespace Demo
{
#region 籠統層,界說了不雅察者形式
/// <summary>
/// (籠統)消息
/// </summary>
public interface INews
{
void SubScribe(ISubscriber s);
void UnSubScribe(ISubscriber s);
void Publish(string newsTitle); //在詳細完成的進程中樹立宣布與定閱的接洽
}
/// <summary>
/// (籠統)定閱者
/// </summary>
public interface ISubscriber
{
void Read(string newsTitle);
}
#endregion
#region 完成層,是對籠統層的詳細完成
/// <summary>
/// (詳細)消息
/// </summary>
public class ITNews : INews
{
private List<ISubscriber> readers = new List<ISubscriber>();
public void SubScribe(ISubscriber s)
{
readers.Add(s);
}
public void UnSubScribe(ISubscriber s)
{
if (readers.Count >= 0)
{
readers.Remove(s);
}
}
public void Publish(string newsTitle)
{
foreach (ISubscriber i in readers)
{
i.Read(newsTitle); //<<<<<宣布的時刻定閱>>>>>
}
}
}
/// <summary>
/// (詳細)定閱者
/// </summary>
public class Subscriber : ISubscriber
{
private string subscriber = string.Empty;
public Subscriber(string subscriber)
{
this.subscriber = subscriber;
}
public void Read(string newsTitle)
{
Console.WriteLine(string.Format("{0}浏覽了IT消息\"{1}\"", subscriber, newsTitle));
}
}
#endregion
public class Pro
{
static void Main(string[] args)
{
ITNews news = new ITNews();
Subscriber zs = new Subscriber("張三"),
ls = new Subscriber("李四"),
ww = new Subscriber("王五");
news.SubScribe(zs);
news.SubScribe(ls);
news.SubScribe(ww);
news.UnSubScribe(ls); //張三撤消定閱
news.Publish("2014年挪動電商攻堅戰:阿裡巴巴若何破局?");
news.Publish("余額寶還能重回高收益率嗎?");
Console.WriteLine();
Console.ReadKey();
}
}
}