观察者模式 ObserverPattern

类图

观察者模式 ObserverPattern_第1张图片

using System; using System.Collections; using System.Collections.Generic; abstract class PaperBusiness { ArrayList customerList=new ArrayList(); public void addCustomer(customer customer) { customerList.Add(customer); } public void removeCustomer(customer customer) { if (customerList.IndexOf(customer) != -1) customerList.Remove(customer); } public void NoticeCustomer() { foreach (customer c in customerList) { c.Noticy(); } } }

观察者抽象

using System; class ChinaPaperBusiness : PaperBusiness { private string _chairManName; private int _worksNumber; public string ChairManName { get { return _chairManName; } set { _chairManName = value; } } public int WorksNumber { get { return _worksNumber; } set { _worksNumber = value; } } }

观察者抽象的实现A

interface customer { void Noticy(); }

接收者接口

using System; class Jim : customer { public PaperBusiness _paperBusiness; public Jim(PaperBusiness paperBusiness) { _paperBusiness = paperBusiness; _paperBusiness.addCustomer(this); } #region customer 成员 public void Noticy() { Console.WriteLine("Jim you must take you paper until 18:00 today."); } public void cancelSubScribe() { _paperBusiness.removeCustomer(this); } #endregion }

接收者A

 using System; class Lucy : customer { public PaperBusiness _paperBusiness; public Lucy(PaperBusiness paperBusiness) { _paperBusiness = paperBusiness; _paperBusiness.addCustomer(this); } #region customer 成员 public void Noticy() { Console.WriteLine("Lucy you must take you paper until 18:00 today."); } public void cancelSubScribe() { _paperBusiness.removeCustomer(this); } #endregion }

接收者B

using System; class Tom : customer { private PaperBusiness _paperBusiness; public Tom(PaperBusiness paperBusiness) { _paperBusiness = paperBusiness; _paperBusiness.addCustomer(this); } #region customer 成员 public void Noticy() { Console.WriteLine("Tom you must take you paper until 18:00 today."); } public void cancelSubScrib() { _paperBusiness.removeCustomer(this); } #endregion }

接收者C

using System; using System.Collections.Generic; using System.Text; namespace ObserverPattern { class Program { static void Main(string[] args) { PaperBusiness paperBusiness = new ChinaPaperBusiness(); Jim jim = new Jim(paperBusiness); Tom tom = new Tom(paperBusiness); Lucy lucy = new Lucy(paperBusiness); paperBusiness.NoticeCustomer(); jim.cancelSubScribe(); Console.WriteLine(); paperBusiness.NoticeCustomer(); Console.ReadKey(); } } }

代码调用者

你可能感兴趣的:(c,String,Class)