Singleton design pattern example in java |
Talk to EasyAssistant |
Singleton design pattern example in java. .
| Singletone:- |
| It's the easiest design pattern. Easy to remember. Using this
design pattern, we make sure that there is only one single object of
a class in the JVAM. This design pattern tells about how to ensure
one single object in the JVM. Practical Use: Singletone design pattern is used to cache the static date (e.g. application property / configuration data) |
Key points of this design pattern is :
package test.easycodeforall.singletone;
import java.io.InputStream;
import java.util.Properties;
public final class PropManager {
private static PropManager obj = new PropManager();
private Properties prop = null;
private String propFileName = "easycodeforall.properties";
private PropManager() {
loadProperties();
}
public void refreshCache() {
loadProperties();
}
private void loadProperties() {
try {
prop = new Properties();
InputStream propAsStream = this.getClass().getResourceAsStream(propFileName);
prop.load(propAsStream);
} catch (Exception ex) {
System.out.println("Unable to load properties from " + propFileName + ". Exception=" + ex);
}
}
public static PropManager getInstance() {
return obj;
}
public String getProperty(String propertyName) {
return prop.getProperty(propertyName);
}
}
Testing:
package test.easycodeforall.singletone;
public class TestSingletone {
public static void main(String[] args) {
System.out.println("Property Value=" + PropManager.getInstance().getProperty("base_folder_name"));
}
}
|
| Post Your Comment: |