lundi 23 juillet 2018

Iterating over subclasses with different properties

I am interested in a design pattern or best practice approach to the following scenario:

Let's say we have multiple subclasses that derive from a common interface:

public interface IPerson{
    string Name;
}

public class SomePerson : IPerson{
    string Name;
    bool hasAccess;

    bool GetAccessInfo(){
    //implementation
    }
}


public class OtherPerson : IPerson{
    string Name;
    int NumberOfPoints;

    int GetNumberOfPoints(){
    //implementation
    }
}

Now let's assume we have a class which has a collection of IPerson objects:

public class PersonHandler{
     public List<IPerson> People;
}

So the question here is how would you iterate over the People collection and still be able to use the individual subclasses' members and methods like GetNumberOfPoints or GetAccessInfo all in one iteration?

I don't like checking the type explicitly and I also don't like having the subclass specific methods be in the interface, because it kind of defeats the purpose of OO design.

Maybe ideally those shouldn't be in the same collection? I'm looking for a language agnostic answer.

Aucun commentaire:

Enregistrer un commentaire