Strategy Pattern
Dependency Injection control the strategy that is being applied to the logic
package designpatterns.strategy;
public class Template {
public final String color;
public final String templateName;
public Template(String color, String templateName) {
this.color = color;
this.templateName = templateName;
}
@Override
public String toString() {
return templateName;
}
}
package designpatterns.strategy;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class TemplateSorter {
public List<Template> sortTemplate(List<Template> templates, Comparator<Template> sortingStrategy) {
return templates.stream().sorted(sortingStrategy).collect(Collectors.toList());
}
public static class Strategy {
public static Comparator<Template> ascendingByName() {
return Comparator.comparing(template -> template.templateName);
}
public static Comparator<Template> descendingByName() {
return (templateA, templateB) -> templateB.templateName.compareTo(templateA.templateName);
}
}
}
package designpatterns.strategy.test;
import designpatterns.strategy.Template;
import designpatterns.strategy.TemplateSorter;
import org.junit.jupiter.api.Test;
import java.util.List;
public class TemplateSorterTest {
@Test
void endToEnd_givenTemplateSorter_shouldSort() {
TemplateSorter templateSorter = new TemplateSorter();
List<Template> templateList = List.of(new Template("red", "c"), new Template("blue", "a"));
System.out.println(templateSorter.sortTemplate(templateList, TemplateSorter.Strategy.descendingByName()));
}
}