Re-implementing OOP design patterns
In this section, we are going to review some of the GOF patterns in light of the new features available in Java 8 and 9.
Singleton
The singleton pattern can be re-implemented by using closure and Supplier<T>
. The Java hybrid code can make use of the Supplier<T>
interface, such as in the following code, where the singleton is an enum (according to functional programming, the singleton types are those that have only one value, just like enums). The following example code is similar to the one from chapter 2, Creational Patterns:
jshell> enum Singleton{ ...> INSTANCE; ...> public static Supplier<Singleton> getInstance() ...> { ...> return () -> Singleton.INSTANCE; ...> } ...> ...> public void doSomething(){ ...> System.out.println("Something is Done."); ...> } ...> } | created enum Singleton jshell> Singleton.getInstance().get().doSomething(); Something is Done.
Builder
The Lombock library introduces the...