通过实现读者,出版社,报纸之间的关系,实践设计模式中的观察者模式。
1.Person类
public class Person { public string Name { get; set; } public Newspaper Newspaper { get; set; } public Person(string name) { this.Name = name; } public void SetNewspaper(Newspaper paper) { this.Newspaper = paper; } }
2.Newspaper类
public class Newspaper { public string Title { get; set; } public string Content { get; set; } public Newspaper(string title, string content) { this.Title = title; this.Content = content; } }
3.Publisher
public class Publisher { public string Name { get; set; } public Publisher(string name) { this.Name = name; } public List<Person> Persons = new List<Person>(); public void SendNewspaper(Newspaper paper) { Persons.ForEach(person=>person.SetNewspaper(paper)); } }
4.main函数
class Program { static void Main(string[] args) { Publisher p = new Publisher("出版社"); p.Persons.Add(new Person("April")); p.Persons.Add(new Person("harris")); p.SendNewspaper(new Newspaper ("人民日报","为人民服务")); } }
1.观察模式又叫订阅\发布模式。
2.Publisher类维护一个读者列表,发布Newspaper时,遍历这个列表,实施发布。
3.Publisher类不承担读者注册的责任,读者在类外部注册到读者列表中,使得Publisher类的代码耦合性较低。