Code Robo
Virtual Service
Comparator
Tester
Converter
Utility
Java Code Complience
Validator
Formatter
EncoderDecoder



Singleton design pattern example in java
       Talk to EasyAssistant

Singleton design pattern example in java. .


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 :
  1. Make the constructor private so that it can not be instantiated from other class
  2. Make the class final so that no other class can not extend this class.
  3. Have a static method (e.g. getInstance()) to get the instance to access of the class and this method will retun the same object alwyas.
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:
Name :
Email ( Optional) :
Comments / Suggestion (* Required) It is required: :
: