mercredi 25 novembre 2020

Storing and iterating through a collection of objects with unrelated interfaces?

I have a group of POJOs that are unrelated in their interface (ex. one might store an int and a boolean, one may store only a String, etc.). They are, however, logically part of the same group - they are objects representing different types of updates with different data models depending on the specific type of update. I want to have a collection of these "update" objects and iterate through them, handling each concrete event differently depending on the class.

My thought on how to approach this is to use the visitor pattern, but I wasn't sure if the visitor pattern can/should be used with objects that aren't directly inheriting from the same superclass or implementing a common interface. Is having an interface like below where the only unifying factor is the accept method a valid approach, or is there a better-suited design approach for a case like this? I would then presumably have a Collection<Update> which I would iterate over.

public interface Update {
   public void accept(UpdateVisitor visitor);
}

Aucun commentaire:

Enregistrer un commentaire