Java Switch on Steroids
Java Switch on Steroids
Join the DZone community and get the full member experience.
Join For Free"I love writing authentication and authorization code." ~ No Developer Ever. Try Okta Instead.
For example let's suppose you need a strategy that switchs among three sorting algorithms based on some characteristic of the list to be sorted. In particular let's assume we have an algorithm specialized for Strings:
public List<String> sortStrings(List<String> list) {another one that works well with small lists having no more than 100 items:
// a sort algorithm suitable for Strings
}
public List<T> sortSmallList(List<T> list) {and a more general purpose one:
// a sort algorithm suitable for no more than 100 items
}
public List<String> sort(List<String> list) {Given these 3 sorting methods it is possible to create a strategy that chooses the most suitable of them in the following declarative way:
// a generic sort algorithm
}
Switcher<List<T>> sortStrategy = new Switcher<List<T>>()In this way it is possible to sort a list using the best available algorithm by invoking the Switcher as it follows:
.addCase(having(on(List.class).get(0), instanceOf(String.class))),
new Closure() {{ of(this).sortStrings(var(List.class)); }})
.addCase(having(on(List.class).size(), lessThan(100))),
new Closure() {{ of(this).sortSmallList(var(List.class)); }})
.setDefault(new Closure() {{ of(this).sort(var(List.class)); }});
List<T> sortedList = sortStrategy.exec(list, list);In this case, the list must be passed twice to the Switcher: once to decide, through the hamcrest Matchers, which sorting method should be used and once to be passed to the closure that will actually do the sort.
The release 2.2 of lambdaj also allows to define blocks that invoke constructors. By using this last feature, it is easy to define a Switcher implementing a factory pattern, that creates different objects based on different conditions once again defined through hamcrest matchers.
"I love writing authentication and authorization code." ~ No Developer Ever. Try Okta Instead.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}