观察者模式——问题案例——双耦合代码

秘书类——Secretary

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_PublishOrSubscribe_Model
{
    //秘书
    class Secretary
    {
        private IList<StockObserver> observers = new List<StockObserver>();
        private string action;
        public void attch(StockObserver observer)
        {
            observers.Add(observer);
        }
        //通知-notfiy
        public void notify()
        {
            foreach (StockObserver o in observers)
            {
                o.update();
            }
        }
        //前台状态
        public string SecretaryAction
        {
            get { return action; }
            set { action = value; }
        }
    }
}

股票观察者

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_PublishOrSubscribe_Model
{
    class StockObserver
    {
        private string name;
        private Secretary sub;
        public StockObserver(String name,Secretary sub)
        {
            this.name = name;
            this.sub = sub;
        }
        public void update()
        {
            Console.WriteLine("{0} {1} 关闭股票行情 继续工作!",sub.SecretaryAction,name);
        }
    }
}

客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_PublishOrSubscribe_Model
{
    class Program
    {
        static void Main(string[] args)
        {
            Secretary secretary = new Secretary();
            StockObserver o1 = new StockObserver("强爸爸", secretary);
            StockObserver o2 = new StockObserver("强爷爷", secretary);
            secretary.attch(o1);
            secretary.attch(o2);
            secretary.SecretaryAction = "老板回来了!!!";
            secretary.notify();
            Console.ReadKey();
        }
    }
}

总结:前台秘书类需要增加观察者类。观察者类需要前台秘书类。

原创文章 37 获赞 11 访问量 2779

猜你喜欢

转载自blog.csdn.net/qq_39691716/article/details/104172591
今日推荐