Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Dec 21, 2001

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 Properties
object.
 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.
Sumit Nigam
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date