Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 60 new to java public class ProductFactory public static Product createProduct String name switch name case loan return new Loan case stock return new Stock case bond return new Bond default throw new RuntimeException No such product name Here Loan Stock and Bond are all subtypes of Product The createProduct method could have additional logic to configure each created product But the benefit is that you can now create these objects without exposing the constructor and the configuration to the client which makes the creation of products simpler for the client Product p ProductFactory createProduct loan In lambda expressions you can refer to constructors just like you refer to methods by using method references For example heres how to refer to the Loan constructor Supplier Product loanSupplier Loan new Loan loan loanSupplier get Using this technique you could rewrite the previous code by creating a Map that maps a product name to its constructor final static Map String Supplier Product map new HashMap static map put loan Loan new map put stock Stock new map put bond Bond new You can now use this Map to instantiate different products just as you did with the factory design pattern public static Product createProduct String name Supplier Product p map get name if p null return p get throw new IllegalArgumentException No such product name This is quite a neat way to make use of the Java 8 features to achieve the same intent as the factory pattern But this technique doesnt scale very well if the factory method createProduct needs to take multiple arguments to pass on to the product constructors Youd have to provide a diferent functional interface than a simple Supplier These examples make clear that lambdas can be used in many situations in which you might not normally think of applying them Getting in the habit of using lambdas however will make your code shorter clearer and easier to write article This article is adapted from an excerpt of the book Java 8 in Action by Raoul Gabriel Urma Mario Fusco and Alan Mycroft Used with permission learn more The original Gang of Four book on design patterns
You must have JavaScript enabled to view digital editions.