Following example expose using of Observer Pattern with MEF dependency injection.
I will need send to all observers XmlElement I got from WebService.
Interfaces of Observer Pattern:
And Concrete of Subject interface:
I will need send to all observers XmlElement I got from WebService.
Interfaces of Observer Pattern:
public interface IResponceObserver { void Update(); }
public interface IResponceSubject { List<IResponceObserver> Observers { get; set; } void Attach(IResponceObserver observer); void Detach(IResponceObserver observer); void Notify(); }
And Concrete of Subject interface:
public class ResponceSubject: IResponceSubject { public List<IResponceObserver> Observers { get; set; } public void Attach(IResponceObserver observer) { Observers.Add(observer); } public void Detach(IResponceObserver observer) { Observers.Remove(observer); } public void Notify() { foreach (IResponceObserver o in Observers) { o.Update(); } } }
Suppose we have two observer classes that need to realize Update() method:
[Export(typeof(IResponceObserver))]public class LoginCommandHandler_1 : CommandHandlerBase, IResponceObserver {
public void Update()
{
WriteLine ("LoginCommandHandler_1")
}
}
[Export(typeof(IResponceObserver))]public class LoginCommandHandler_2 : CommandHandlerBase, IResponceObserver {public void Update(){WriteLine ("LoginCommandHandler_2")
}}And Main Class that will add observer to List of subject and Notify all observers:public class CustomerServiceAgent : ICustomerServiceAgent { [ImportMany] public IResponceObserver[] ResponseObservers { get; set; }public void SomethingDo() { //REGISTER ALL OBSERVERS WHO WANT TO GET ANY FROM response.Customer IResponceSubject responceSubject = new ResponceSubject(); foreach (var observer in ResponseObservers) { responceSubject.Attach(observer); }//YOUR CODE HERE://UPDATE All Observers with response.Customer.Any responceSubject.Notify(); return customer; }}Output:\> LoginCommandHandler_1
\> LoginCommandHandler_2I hope its help to understand MEF and return against on Observer Pattern
Thanks,
Enjoy!
No comments:
Post a Comment