简单的观察者模式示例分享
程序员文章站
2023-12-20 11:58:58
复制代码 代码如下:using system;using system.collections.generic;namespace demo{ &nb...
复制代码 代码如下:
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();
}
}
}