分析详见:http://lvxingzhelimin.blog.163.com/blog/static/1707165502011101655652697/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//老板胡汉三
Boss huhansan = new Boss() ;
//看股票的同事
StockObserver tongshi1 = new StockObserver("魏关拆",huhansan);
NBAObserver tongshi2 = new NBAObserver("易观查",huhansan);
huhansan.Attach(tongshi1 );
huhansan.Attach(tongshi2);
huhansan.Detach(tongshi1);
//老板回来
huhansan.SubjectState = "我胡汉三又回来了!";
//发出通知
huhansan.Notify();
Console.Read();
}
}
}
//通知者接口
interface Subject
{
void Attach(Observer observer);
void Detach(Observer observer);
void Notify();
string SubjectState
{
get;
set;
}
}
//老板类
class Boss :Subject
{
//同事列表
private IList< Observer > observers = new List < Observer >();
private string action;
//增加
public void Attach(Observer observer)
{
observers.Add(observer );
}
//减少
public void Detach(Observer observer)
{
observers.Remove(observer );
}
//通知
public void Notify()
{
foreach (Observer o in observers)
o.Update();
}
//老板类的状态
public string SubjectState
{
get { return action; }
set { action = value; }
}
}
//抽象观察者
abstract class Observer
{
protected string name;
protected Subject sub;
//构造方法,指明观察者姓名建立和通知者间的关联
public Observer(string name,Subject sub)
{
this.name = name;
this.sub = sub;
}
//定义抽象方法——更新
public abstract void Update();
}
//看股票的同事
class StockObserver : Observer
{
//首先建立与继承的父类的最基本的属性设置
public StockObserver(string name,Subject sub ):base (name,sub )
{
}
//看股票同事的更新事件,重写父类的Update方法。
public override void Update()
{
Console.WriteLine("{0} {1} 关闭股票行情,继续工作!",sub .SubjectState,name);
}
}
//看NBA的同事
class NBAObserver : Observer
{
//添加一个构造方法,指定看NBA同事这个类的姓名和与之关联的观察者
public NBAObserver(string name,Subject sub)
: base(name,sub)
{
}
//重写更新方法
public override void Update()
{
Console.WriteLine("{0}{1}关闭NBA,继续工作!",name );
}
}
原文链接:https://www.f2er.com/javaschema/287040.html