前言
观察者模式
观察者模式:定义了一种对象之间的一对多依赖关系,消息发布者发布通知时,它的所有订阅者(依赖)对象都会自动收到通知并进行相应的更新。
代码
//抽象观察者类
public abstract class Observer
{protected string name;public string Name { get { return name; } }public Observer(string name){this.name = name;}public abstract void Update(string message);
}//具体观察者类1:主题订阅类
public class SubscribeSubject : Observer
{public SubscribeSubject(string name) : base(name){}public override void Update(string message){Console.WriteLine($"[{name}] received a subject message : {message}");}
}
//具体观察者类2:消息订阅类
public class MessageReceiver : Observer
{public MessageReceiver(string name) : base(name){}public override void Update(string message){Console.WriteLine($"[{name}] received a subject message : {message}");}
}//(抽象)主题接口
public interface Subject
{void Attch(Observer observer);void Detach(Observer observer);void NotifyObservers(string message);
}
//具体主题:发布主题类
public class PublishSubject : Subject
{public List<Observer> Observers = new List<Observer>();public void Attch(Observer observer){Observers.Add(observer);Console.WriteLine($"Add an subscriber[type={observer.GetType().Name}],[ name = {observer.Name}]");}public void Detach(Observer observer){Observers.Remove(observer);Console.WriteLine($"Removes an subscriber: {observer.Name}");}public void NotifyObservers(string message){Console.WriteLine($"publish a notify:{message}");foreach (var item in Observers){item.Update(message);}}
}/** 行为型模式:Behavioral Pattern* 观察者模式:Observer Pattern*/
internal class Program
{static void Main(string[] args){//创建观察者Observer observer1 = new SubscribeSubject("User1");Observer observer2 = new SubscribeSubject("User2");Observer observer3 = new SubscribeSubject("User3");Observer observer4 = new SubscribeSubject("User4");Observer observer5 = new MessageReceiver("User5");//创建发布者Subject pubulisher = new PublishSubject();//发布者记录观察者pubulisher.Attch(observer1);pubulisher.Attch(observer2);pubulisher.Attch(observer3);pubulisher.Attch(observer4);pubulisher.Attch(observer5);//发布消息Console.WriteLine();pubulisher.NotifyObservers("Hellow users.");Console.WriteLine();pubulisher.Detach(observer1);Console.WriteLine();pubulisher.NotifyObservers("see you again,users!");Console.ReadLine();}
}