In this video, Venkat Subramaniam revisits a few patterns from the book by the Gang of Four and adapts them to the new features in Java.

https://www.youtube.com/watch?v=V7iW27F9oog

Optional - Patterns and Anti-Patterns

Using an Optional as an input to a method is an anti-pattern as it involves writing extra code when calling that method

public void setSomething(Optional<Integer> number) {
	...
}

setSomething(Optional.empty())
setSomething(Optional.of(...)

Similarly, returning an Optional is not fool-proof, as a method may return a null.

public Optional<> getSomething() {
	return null;
}

Factory Pattern

Java interfaces allow defining a default implementation of a method that can invoke the interface method.


public interface Pet {

	public String getName();

	default String playWithPet() {
			return "Playing with " + getName();
	}

}

Strategy Pattern

The example used here involves

public Integer addNumbers(List<Integer> numbers, Function<Integer,Boolean> strategy) {

	Integer result = 0;

	for (var i: numbers) {
		if (strategy.call(i))
			result += i;
	}

	return result;

}