lundi 24 septembre 2018

How to use strategy pattern with custom sorting strategies?

I would like to know if the approach that I am using is the best or not for this situation.

I'm developing a REST API and I have an endpoint which has to return a list of person objects. Let's say that person class has age (int), hair and vegan (both booleans), for example.

That endpoint should return persons sorted by age (younger first), if they have the same age, then those who have hair, and then those who are vegan.

That sorting strategies can be changed, as they are read from configuration file. So the endpoint could have to return first those who are vegan, then those who have hair and then by age.

As I see there are different strategies to be applied, I thought that the best approach would be use strategy pattern (I also considered decorator but as the strategy can be changed I don't know how to apply it). I created a interface which returns a comparator, and then I have the strategies implementation that can be applied (hair, age and vegan), which return a comparator. I read the strategies from a configuration file and I save them into a string array.

As at this moment there are only three strategies I use

array.stream.sorted(strategy[0].compare().thenComparing(strategy[1].compare()).thencomparing...)

but I see a obvious problem, that this is not escalable, because if I add one strategy more it would not be processed.

So I have two questions here, is strategy pattern the best design pattern for this situation of sorting? And how could I proceed to make more generic the strategies array that are applied?

Aucun commentaire:

Enregistrer un commentaire