设为首页 加入收藏

TOP

设计模式-观察者设计模式(二)
2019-09-20 11:46:10 】 浏览:89
Tags:设计模式 观察者
Console.WriteLine(
"{0} Run", this.GetType().Name); } } public class Neighbor : IObserver { public void Action() { this.Awake(); } public void Awake() { Console.WriteLine("{0} Awake", this.GetType().Name); } } public class Stealer : IObserver { public void Action() { this.Hide(); } public void Hide() { Console.WriteLine("{0} Hide", this.GetType().Name); } } View Code

Cat这个类就可以修改成如下,使用集合或者事件都是可以的:

public class Cat
{
    //Cat不稳定--这一堆对象--甩锅--自己不写让别人传递
    private List<IObserver> _ObserverList = new List<IObserver>();
    public void AddObserver(IObserver observer)
    {
        this._ObserverList.Add(observer);
     MiaoHandler += observer.Action; }
public void MiaoObserver() { Console.WriteLine("{0} MiaoObserver.....", this.GetType().Name); if (this._ObserverList != null && this._ObserverList.Count > 0) { foreach (var item in this._ObserverList) { item.Action(); } } } private event Action MiaoHandler; public void MiaoEvent() { Console.WriteLine("{0} MiaoEvent.....", this.GetType().Name); if (this.MiaoHandler != null) { foreach (Action item in this.MiaoHandler.GetInvocationList()) { item.Invoke(); } } } }

这样在调用的时候,增加一个,减少一个,更改顺序,就不要再去修改Cat类了。

 Cat cat = new Cat();
 cat.AddObserver(new Chicken());
 cat.AddObserver(new Baby());
 cat.AddObserver(new Brother());
 cat.AddObserver(new Dog());
 cat.AddObserver(new Father());
 cat.AddObserver(new Mother());
 cat.AddObserver(new Mouse());
 cat.AddObserver(new Neighbor());
 cat.AddObserver(new Stealer());
 cat.MiaoObserver();

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇设计模式-结构型-桥接模式 下一篇面向切面编程AOP

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目