Thursday, November 3, 2011

Observer Pattern with Managed Extensibility Framework (MEF)

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:


public interface IResponceObserver
{
        void Update();
}

public interface IResponceSubject
{
        List<IResponceObserver> Observers { getset; }
        void Attach(IResponceObserver observer);
        void Detach(IResponceObserver observer);
        void Notify();
}



And Concrete of Subject interface:


public class ResponceSubjectIResponceSubject
{
        public List<IResponceObserver> Observers { getset; }
        
        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 getset; }

        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_2

I hope its help to understand MEF and return against on Observer Pattern

Thanks,
Enjoy! 

No comments:

Post a Comment