当前位置: 编程技术>.net/c#/asp.net
简单的观察者模式示例分享
来源: 互联网 发布时间:2014-10-29
本文导语: 代码如下:using System;using System.Collections.Generic;namespace Demo{ #region 抽象层,定义了观察者模式 /// /// (抽象)新闻 /// public interface INews { void SubScribe(ISubscriber s); void UnSubScribe(ISubscrib...
代码如下:
using System;
using System.Collections.Generic;
namespace Demo
{
#region 抽象层,定义了观察者模式
///
/// (抽象)新闻
///
public interface INews
{
void SubScribe(ISubscriber s);
void UnSubScribe(ISubscriber s);
void Publish(string newsTitle); //在具体实现的过程中建立发布与订阅的联系
}
///
/// (抽象)订阅者
///
public interface ISubscriber
{
void Read(string newsTitle);
}
#endregion
#region 实现层,是对抽象层的具体实现
///
/// (具体)新闻
///
public class ITNews : INews
{
private List readers = new List();
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); //
}
}
}
///
/// (具体)订阅者
///
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();
}
}
}