Factory Pattern, The dynamic way with Java 8
Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
Let us take an example of loyalty Tier represents the level of member
To get instances of Tier based on some criteria without specifying the concrete implementation we can use the Factory pattern as following:
But here.. we have a problem!. adding a new type we need to update the factory implementation, and this is a break of Open / Close principle (OCP).
A simple solution for this is dynamic registration of types and initialize instances with Java reflection
This is “good” and it works but Java reflection is not a good creature, it may the code performance even to 10%! also we need to make sure the concrete classes are loaded by class loader before accessing them from factory or they will not be registered, this can be done by calling Class.forName somewhere in the code statically (like what we do in JDBC driver)
Java 8 provides a handy utilities to support functional programming and other aspects of development, we will utilize Supplier functional interface to dynamically register tier types into our factory.
Supplier interface provide a single method to return object of some class
a simple and direct implementation. so instead of registering classes and using reflection in our Factory, we will instead register Supplier instances and get our object instances directly by get() call.
we defined the BlueSupplier as following
now we can dynamically register Tier suppliers with this definition like
or using Lambda
or even using method reference
This was a basic demonstration of the Factory pattern and dynamic registration with both (painful) reflection and flexible supplier interface provided by Java 8.
Any questions? Comment and let us know.