Design Patterns – DI or Factory Pattern? Both? Or a Different Approach?

asp.netcdependency-injectiondesign-patterns

Lets say we have an abstract class called BaseSwitch, inherited by concrete implementations Switch A and Switch B, Each Switch representing a real-life switch (A telephony tool which among its responsibilities is writing CDR; all data records of calls hitting the switch).

Each Switch in real life writes CDR in a different format and to different sources, say some switch writes to a text file another writes to a MySQL database.

The Switches as entities and CDR details are defined by the system's end user

My goal is writing Importer classes responsible for importing CDR based on the source of the data determined by the switch entity into my system, but hiding the Importer from the switch classes.

The layer responsible for importing the CDR will loop upon switches, and instatiate an 'Importer' object, based on the CDR format defined in each switch.

Can anyone suggest an approach to use ?

EDIT :
More clarification Below :

public class SwitchBase
{
public abstract string CDRFormat { get; }
}

public class SwitchA:SwitchBase
{
    public override string abc
    {
        get { return "Text"; }
    }


}

public class SwitchB : SwitchBase
{
    public override string CDRFormat
    {
        get { return "MySQLDatabase"; }
    }
}


public class CDR
{ }

public class MySQLImporter
{
    ICollection<CDR> GetCDR()
    {
        //DoSomething
    }
}

public class TextImporter
{
    ICollection<CDR> GetCDR()
    {
        //DoSomething
    }
}

Best Answer

The Factory Pattern allows objects having different types but conforming to the same interface to be created, the specific type which is created being based on some condition. Seems particularly appropriate here.

So create some static methods with different overloads that each accept a different parameter signature and return the appropriate object (polymorphism), or create a single static method and put a switch statement in it that switches over a method parameter and returns the appropriate object.

public static class MyCDRFactory
{
    public static ICDRInterface Create(CDRFormat format)
    {
        switch (format)
            case CDRFormat.Alpha: return new CDRAlpha();

            case CDRFormat.Beta: return new CDRBeta();

        // ..etc
    }
}

ICDRInterface implementations:

public Class CDRAlpha: ICDRInterface
{
    // Implementation for Alpha format goes here
}


public Class CDRBeta: ICDRInterface
{
    // Implementation for Beta Format goes here
}

Usage:

var processor = MyCDRFactory.Create(CDRFormat.Alpha);
Related Topic