c#中的观察者设计模式

//观察者模式

interface Subject

{

 void Notify();

 string SubjectState{set;get;}

}

//事件委托管理

delegate void PatrolHandle();

class Teacher :Subject

{

  //事件和委托最主要的区别就是事件不能当做形参传递,但是委托可以

public event PatrolHandle Update;

public string SubjectState{set;get;}

public void Notify()

{

  if(Update != null)

{

Update();

}

}

}


//订阅者

class PlayOberserver

{

private string name;

private Subject sub;

public PlayOberserver(string name,Subject sub)

{

this.name =name;

this.sub =sub;

}

public void PlayPhone()
        {
            Console.WriteLine("{0}{1}放下手机,假装写代码",sub.SubjectState,this.name);
        }

}

}


class ViewOberserver

{

private string name;

public Subject sub;

public ViewOberserver(string name,Subject sub)

{

this.name =name;

this.sub =sub;

}

public void Watch()

{

 Console.WriteLine("{0}{1}关闭视频窗口,假装写代码", sub.SubjectState, this.name);

}

//主函数实现


  Teacher t =new Teacher();

  PlayOberserver po =new  PlayOberserver("张三",t);//这里传入Teacher对象,里氏替换原则

  ViewOberserver vb = new ViewOberserver("李四",t);


//监听事件

t.Update +=new PatrolHandle(po.PlayPhone);

t.Update += vb.WatchView;


//老师来了

t.SubjectState ="七点了,老师来查班了";

//调用方法,发布通知

t.Notify();

}









你可能感兴趣的:(c#学习)