标签:
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { A a = new B(); a.Say(); a.SetAction(new ActionB()); a.Say(); a = new C(); a.Say(); Console.Read(); } } public interface TheAction { void Say(); } public abstract class A { public TheAction theAction; public void Say() { theAction.Say(); } public void SetAction(TheAction a) { theAction = a; } } public class B : A { public B() { theAction = new ActionA(); } } public class C : A { public C() { theAction = new ActionB(); } } public class ActionA : TheAction { public void Say() { Console.WriteLine("Action A"); } } public class ActionB : TheAction { public void Say() { Console.WriteLine("Action B"); } } }
using System; using System.Collections.Generic; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Observer o = new Observer(); Subject s = new Subject(o); o.SetA("Hello World"); o.SetA("Have a good day"); Console.Read(); } } public class Observer { public List<Subject> subjects; public Observer() { subjects = new List<Subject>(); } public string A { get; set; } public void Regist(Subject subject) { subjects.Add(subject); } public void UnRegist(Subject subject) { subjects.Remove(subject); } public void notifyObservers() { foreach (var item in subjects) { item.Update(A); } } public void SetA(string a) { A = a; notifyObservers(); } } public class Subject { public Observer observer; public Subject(Observer o) { observer = o; observer.Regist(this); } public string A { get; set; } public void Update(string a) { A = a;Display(); } public void Display() { Console.WriteLine(A); } } }
标签:
原文地址:http://www.cnblogs.com/CodingArt/p/4215167.html