Factory With Java 8

Consider an application that prints student names taken from a data access object.

The application can work with different data stores and the storage should not affect the operations performed. That’s why there is an interface DataAccess that provides the data and several implementations (in this case two) that know how to handle the reading from the actual data storage.

Another part of the application is the DataProcessor that prints students obtained from the DataAccess. The DataProcessor does not care what is the actual storage it needs just the data (the students’ names).

Here is a sample implementation:

Source: DataProcessor.java

Source: DataAccess.java

Source: MongoAccess.java

Source: RdbmsAccess.java

Here is how a main app would look like written in Java 7. First a Factory class that creates a DataAccess is required:

Source: Factory.java

and an Application that actually uses the DataProcessor

Source: Application.java

This code can consist of fewer lines if using Java 8 capabilities for Lambdas and the interfaces defined in java.util.function.Supplier

Source: ApplicationWithLambda.java

In this case the Factory class is replaced by java.util.function and the code is inlined using a lambda expression.
This code is more compact that the one using Java 7 but it can become event more compact using method references.

Source: ApplicationWithLambda.java

Here the Supplier is inlined using a method reference to the constructor of each data access class. A nice benefit of this approach is that in case of not supported type it is easy the show a readable error displaying all supported types.

You can find the full code here

Leave a Reply

Your email address will not be published. Required fields are marked *