mercredi 19 septembre 2018

Creation/Design Pattern for IDisposable classes

This is more of a general design pattern question. I have a IDisposable class that takes a single component in its constructor and does work with it in the constructor. I'd like to refactor this class to also be able to deal with an IEnumerable. Simplified code below.

public class ResourceManager: IDisposable {
    //Component is disposable object 
    private IEnumerable<Component> m_components;
    private bool disposed = false;

    ResourceManager(Component component): this(new []{component}) 
    {
    }

    ResourceManager(IEnumerable<Component> components) 
    {
        m_components = components;

        //do some other work

        foreach(component in m_components) {
            component.Foo();
        }
    }

    public void Dispose() 
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual Dispose(bool disposing) 
    {
        if (diposed) 
            return;
        if (!disposing)
            return;

        //do some work

        foreach(component in m_components) 
            component.Dispose();

        disposed = true;
    }   
}

One concern I have is that most of the time ResourceManager will be instantiated with a single component so the conversion to an IEnumerable is adding overhead. The ResourceManager is used heavily in logging so I'd like to avoid that.

I'd like to refactor ResourceManager into an AbstractResourceManager and have two concrete implementations, one for a single component and one for multiple which will be created via a ResourceManagerFactory. Except there'd be a lot of repeated code between the two classes since the only difference between the two classes is the presence of the foreach loops to call component.Dipose(). Is there a better way to approach this?

Aucun commentaire:

Enregistrer un commentaire