Using the java.util.Properties Object to Decouple Applications

Using the java.util.Properties Object to Decouple Applications

Assume that you have a set of classes that need to provide the same functionality but the way they provide it is different. In essence, these are the classes that implement the same interface.

The problem lies in writing the logic to decide which of these class to instantiate at runtime. An easy way to design it, while making it totally decoupled, is to store the class names in a properties file which can be loaded into the java.util.Properties object.

Assume that the classes are implementing the interface Intf. And as mentioned their names are already loaded into the Properties object using the load() method.

At runtime, a factory can be used which accepts a parameter to identify the implementing class to be instantiated:

 public class Factory{private Intf interfc;public Intf getObject(String classIdentifier){ // Read the class corresponding to classIdentifier from _the Propertiesobject. Class cls = Class.forName(classIdentifier); interfc = cls.newInstance(); return interfc;}}

The biggest advantage of this approach is that it helps you to totally decouple your application logic from the set of different classes that the factory might instantiate. Moreover, it helps you do away with the ‘if loops’ to decide which class is to be instantiated.

See also  How HealthStream Learning Center Supports Healthcare Education and Compliance

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist