using System;
using System.Collections;
namespace Factory
{
/// <summary>
/// 普通的正常做法
/// </summary>
/*
public class ATM
{
BankAccount bankAccount;
void process(int data)
{
bankAccount.Withdraw(data);
}
}
public class BankAccount
{
Emailer emailer;//紧耦合
Mobile mobile;//紧耦合
public void Withdraw(int d)
{
//...
emailer.SendEmail("email");
mobile.Send("phone");
}
}
public class Emailer
{
public void SendEmail(string to)
{
//...
}
}
public class Mobile
{
public void Send(string phone)
{
}
}
*/
//--------------------------------------------------
//observer pettern设计模式
//--------------------------------------------------
public class UserAccountArgs
{
public string moble;
public string email;
public UserAccountArgs()
{
}
}
---------------------------------------------
--IB
---------------------------------------------
public interface IAccountObserver
{
void Update(UserAccountArgs args);
}
-------------
--B1
------------
public class Emailer:IAccountObserver
{
public void SendEmail(string to)
{
//...
}
public void Update(UserAccountArgs args)
{
string email=args.email;
SendEmail(email);
}
}
--------------
--B2
--------------
public class Mobile:IAccountObserver
{
public void Send(string phone)
{
}
public void Update(UserAccountArgs args)
{
string mobile=args.moble;
Send(mobile);
}
}
--------------------------------------------------------------------
--A1
---------------------------------------------------------------------
public class BankAccount:Subject
{
UserAccountArgs userAccount;
public void Withdraw(int d)
{
userAccount=new UserAccountArgs();
Notify(userAccount);
}
}
--------------------------------------------------
-把稳定的操作抽出来 IA
--------------------------------------------------
public abstract class Subject
{
ArrayList IAccountList=new ArrayList();
public void Add(IAccountObserver Ia)
{
IAccountList.Add(Ia);
}
public void Remove(IAccountObserver Ia)
{
IAccountList.Remove(Ia);
}
public virtual void Notify(UserAccountArgs userAccount)
{
foreach(IAccountObserver Ia in IAccountList)
{
Ia.Update(userAccount);
}
}
}
}