Reputation: 4425
I have a case that I want return an object that is populated by multiple concrete classes.
Specific example:
public interface MovieHandler {
UserPreferences process(Context context, Customer customer, History customerHistory);
}
Concrete implementations:
public class AdventureMovieHandler implements MovieHandler
public class ComedyMovieHandler implements MovieHandler
public class MysteryMovieHandler implements MovieHandler
public class SciFiMovieHandler implements MovieHandler
Each has their own logic so that based on the parameters passed in the process
the create a list of recommendation for the specific category/genre.
There is also:
public class Recommender {
private List<UserPreferences> handlers;
public Recommender() {
handlers = new ArrayList<>();
handlers.add(new AdventureMovieHandler());
handlers.add(new ComedyMovieHandler());
handlers.add(new SciFiMovieHandler());
handlers.add(new MysteryMovieHandler());
}
public UserPreferences getRecommendations(Context context, Customer customer, History customerHistory) {
UserPreferences preferences = new UserPreferences();
for(MovieHandler handler: handlers) {
UserPreferences r = handler.process(context, customer, customerHistory);
if(r.getMysteryInfo() != null) {
preferences.setMysteryInfo(r.getMysteryInfo());
}
else if(r.getAdventureInfo() != null) {
preferences.setAdventureInfo(r.getAdventureInfo());
}
else if(r.getComedyInfo() != null) {
preferences.setComedyInfo(r.getComedyInfo());
}
else if(r.getSciFiInfo() != null) {
preferences.setSciFiInfo(r.getSciFiInfo());
}
preferences.getMovies().addAll(r.getMovies());
}
return preferences;
}
}
And the UserPreferences
.
public class UserPreferences {
private MysteryGenre mysteryInfo;
private AdventureGenre adventureInfo;
private ComedyGenre comedyInfo;
private SciFiGenre sciFiInfo;
List<Movie> movies;
Now this works but I am not sure if the implementation of the Recommender
could use some design pattern that helps avoiding checking for what is null
per case in the series of if/else
.
Is there something suited that can be used for this case?
Please note that I need to return that UserPreferences
in that format i.e. as a holder for all the various cases
Upvotes: 0
Views: 82