观察站模式
依赖倒置原则
依赖抽象,尽可能扩展而不是修改和破坏
public abstract class Subject { IList<IAccountObserver> observerList = new List<IAccountObserver>(); public void AddObserver( IAccountObserver observer ) { observerList.Add( observer ); } public void RemoveObserver( IAccountObserver observer ) { observerList.Remove( observer ); } public void Notify( UserAccountArgs args ) { foreach( IAccountObserver observer in observerList ) { observer.Update( args ); } } }
public class UserAccountArgs { public string PhoneNumber; public string Email; }
public class BankAccount : Subject { public void WithDraw( UserAccountArgs args ) { Notify( args ); } }
public interface IAccountObserver { void Update(UserAccountArgs args); }
public class Mobile:IAccountObserver { public void Update( UserAccountArgs args ) { } }
public class Emailer:IAccountObserver { public void Update( UserAccountArgs args ) { } }
调用
static void Main( string[] args ) { Subject subject = new BankAccount(); UserAccountArgs arg = new UserAccountArgs(); arg.Email = ""; arg.PhoneNumber = ""; IAccountObserver observer1 = new Emailer(); IAccountObserver observer2 = new Mobile(); subject.AddObserver( observer1 ); subject.AddObserver( observer2 ); subject.Notify( arg ); }
为了原则而模式不是为了模式而代码
posted on 2013-04-15 14:04 HOT SUMMER 阅读(141) 评论(0) 编辑 收藏 举报