lundi 21 août 2017

Where to insert an EventHandler in factory pattern

I'm quiet new in design pattern and I have a question about the abstract factory pattern. I'm trying to build a connection with a database that receives data through the network, but I have a problem with the design of this architecture. I need to attach an event to this element in order to receive the state changing, but I don't know how to draw the class diagram.

I have the main abstract class:

 public abstract class NetItem
{

    public abstract void Connect();
    public abstract void Disconnect();
    public abstract void Close();

    // THIS SHOULDN'T BE HERE
    public abstract void AttachConnectionStateChanged(IConnectionStateChanged state);

    // other methods

}


 public interface IConnectionStateChanged
{
    void StateChangedEvent(object sender, MtConnectionEventArgs e);

} 

As you can see in IConnectionStateChanged the eventargs is MtConnectionEventArgs, but I know it's the wrong place for this specialization in the abstract class.
I know I can handle this problem in the concrete class, something like this:

public class MtApiNetItem : NetItem
{
    MtApiClient mtApi = null;
    private MtApiParamsFactory mtApiParamsFactory;

    // Code for handling statechanged
}

But in the main program I would like to write something like this:

MtApiFactory factory = new MtApiFactory()
NetItem myItem = factory.CreateConnection(params...);

because I want to follow the DiP rule:
"Depend on abstractions. Do not depend on concrete classes"

How can I write my diagram class to subscribe to the StateChange event without personalizing the main abstract class?

Could you give me an advice how to manage this problem?

Thank you

Aucun commentaire:

Enregistrer un commentaire