【设计模式】观察者模式

来源:互联网 发布:c 并行编程 pdf 编辑:程序博客网 时间:2024/04/30 17:39

观察者模式:定义对象间的一种一对多的依赖关系,使得每当一个对象改变状态时,则其他相关依赖对象皆得到通知并被自动更新。

实现一:被观察者需要有添加和删除观察者的功能,当被观察者状态变化时,调用其观察者的更新函数。

猫和老鼠

using System;using System.Collections.Generic;using System.Text;using System.Collections;namespace mouseANDcat{    public interface Observer    {        void Response();    }    public interface Subject    {        void AimAt(Observer obs);    }    public class Mouse : Observer    {        private string name;        public Mouse(string name, Subject subj)        {            this.name = name;            subj.AimAt(this);        }        public void Response()        {            Console.WriteLine(name + "努力逃跑!");        }    }    public class Cat : Subject    {        private ArrayList observers;        public Cat()        {            observers = new ArrayList();        }        public void AimAt(Observer obs)        {            this.observers.Add(obs);        }        public void Cry()        {            Console.WriteLine("猫叫了!");            foreach (Observer obs in this.observers)            {                obs.Response();            }        }    }    class Program    {        static void Main(string[] args)        {            Cat cat = new Cat();            Mouse mouse1 = new Mouse("小老鼠", cat);            Mouse mouse2 = new Mouse("大老鼠", cat);            cat.Cry();            Console.Read();        }    }}

股票变化

using System;using System.Collections.Generic;using System.Text;using System.Collections;namespace 股票变化{    abstract class Stock    {        protected string symbol;        protected double price;        private ArrayList investors = new ArrayList();        public Stock(string symbol, double price)        {            this.symbol = symbol;            this.price = price;        }        public void Attach(Investor investor)        {            investors.Add(investor);        }        public void Detach(Investor investor)        {            investors.Remove(investor);        }        public void Notify()        {            foreach (Investor i in investors)                i.Update(this);        }        public double Price        {            get { return price; }            set            {                price = value;                Notify();            }        }        public string Symbol        {            get { return symbol; }            set { symbol = value; }        }    }    class IBM : Stock    {        public IBM(string symbol, double price) : base(symbol, price) { }    }    interface IInvestor    {        void Update(Stock stock);    }    class Investor : IInvestor    {        private string name;        private Stock stock;        public Investor(string name)        {            this.name = name;        }        public void Update(Stock stock)        {            Console.WriteLine("通知到股民{0} {1} 最新股价为:{2:C}", name, stock.Symbol, stock.Price);        }        public Stock Stock        {            get { return stock; }            set { stock = value; }        }    }    class Program    {        static void Main(string[] args)        {            Investor s = new Investor("张三");            Investor b = new Investor("李四");            IBM ibm = new IBM("IBM", 120.00);            ibm.Attach(s);            ibm.Attach(b);            ibm.Price = 120.10;            ibm.Price = 121.00;            ibm.Price = 120.50;            ibm.Price = 120.75;            Console.Read();        }    }}


二:利用C#的事件委托,被观察者中无需添加和删除观察者函数。

using System;using System.Collections.Generic;using System.Text;namespace 委托实现观察者模式{    class StockObserver    {        private string name;        private Subject sub;        public StockObserver(string name, Subject sub)        {            this.name = name;            this.sub = sub;        }        public void CloseStockMarket()        {            Console.WriteLine("{0} {1} 关闭股票行情,继续工作!", sub.SubjectState, name);        }    }    class NBAobserver    {        private string name;        private Subject sub;        public NBAobserver(string name, Subject sub)        {            this.name = name;            this.sub = sub;        }        public void CloseNBADirectSeeding()        {            Console.WriteLine("{0} {1} 关闭NBA直播,继续工作!", sub.SubjectState, name);        }    }    interface Subject    {        void Notify();        string SubjectState        {            get;            set;        }    }    delegate void EventHandler();    class Boss : Subject    {        public event EventHandler Update;        private string action;        public void Notify()        {            Update();        }        public string SubjectState        {            get { return action; }            set { action = value; }        }    }    class Program    {        static void Main(string[] args)        {            Boss huhansan = new Boss();            StockObserver tongshi1 = new StockObserver("魏关姹", huhansan);            NBAobserver tongshi2 = new NBAobserver("易管查",huhansan);            huhansan.Update += new EventHandler(tongshi1.CloseStockMarket);            huhansan.Update += new EventHandler(tongshi2.CloseNBADirectSeeding);            huhansan.SubjectState = "我胡汉三回来了!";            huhansan.Notify();            Console.Read();        }    }}