0

I have situation that 3 different instances with the same method signature are doing their job repeatedly.

interface IArgs{
    //args stuff
}

interface IExample{
    void Populate(IArgs);
}

class ExampleA : IExample
{
    void Populate(IArgs a){
        //todo
    }
}

class ExampleB : IExample
{
    void Populate(IArgs b){
        //todo
    }
}

class ExampleC : IExample
{
    void Populate(IArgs c){
        //todo
    }
}


class MainExampleClass(){
    ExampleA classA;
    ExampleB classB;
    ExampleC classC;
    //instantiation and other class stuff
    foreach(Data data in dataCollection){
        classA.Populate(data);
        classB.Populate(data);
        classC.Populate(data);
    }
}

It's worth to mention that the classes work with different args but I solve that with one dataholder class with all arguments and implementation of an interface (IArgs). So my question is: is there any good way, practice, pattern to solve this repeatedly calling of methods? The Factory pattern, if I understood, will return one instance, but here I need all 3. Any suggestions would be appreciated.

1
  • 3
    I find this question confusing. You are using polymorphism for IArgs, but you seem to completely miss polymorphism for IExample? Don't overthink this problem, simple array and foreach will solve your problem.
    – Euphoric
    Feb 19, 2019 at 10:05

1 Answer 1

3

Create an array/list of your classes, with their common interface. You can then iterate over it every time you want to Populate your classes:

class MainExampleClass(){
    ExampleA classA;
    ExampleB classB;
    ExampleC classC;
    //instantiation and other class stuff
    var classes = new IExample[] { classA, classB, classC };
    foreach(Data data in dataCollection){
        foreach (var class_ in classes) {
            class.Populate(data);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.