Java Design Pattern – Singleton Pattern

“In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This concept is also sometimes generalized to restrict the instance to more than one object, as for example, we can restrict the number of instances to five objects. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist. It is also considered an anti-pattern by some people, who feel that it is overly used, introducing unnecessary limitations in situations where a sole instance of a class is not actually required.” [Source Wikipedia]

In the following demo, I have tried to explain via code, how Singleton Pattern can be implemented in Java. The comments are self explanatory.

package com.kushal.patternsexample;
/**
 * Main class for testing singleton pattern.
 *
 */
public class SingletonTestMain
{
	public static void main(String args [])
	{
		/**This creates a fresh object*
		 * Constructor will be called.
		 */
		JavaSingletonObject obj=JavaSingletonPattern.getJavaSingletonObject();
		obj.printMe();

		/**
		 * We already have object created.
		 * This method call wont call constructor.
		 */
		obj=JavaSingletonPattern.getJavaSingletonObject();
		obj.printMe();

		/**
		 * Let's destroy the method ourselves.
		 */
		JavaSingletonPattern.nullifyJavaSingletonObject();

		/**
		 * Now, we try to create object again.
		 * This time, construction will be called, as the object is null.
		 */
		obj=JavaSingletonPattern.getJavaSingletonObject();
		obj.printMe();

	}
}

/**
 * This is some kind of factory class, it creates
 * objects of different classes using singleton pattern.
 */
class JavaSingletonPattern {

	private static JavaSingletonObject javaSingletonObject;
	/**
	 * The constructor is private.
	 */
	private JavaSingletonPattern() {
		/* We can have optional code here*/
	}
	public static JavaSingletonObject getJavaSingletonObject() {
		if (javaSingletonObject == null) {
			javaSingletonObject = new JavaSingletonObject();
		}
		return javaSingletonObject;
	}

	/**Just a helper method to nullify the object ourselves.*/
	public static void nullifyJavaSingletonObject()
	{
		javaSingletonObject=null;
	}
}

/**
 * @author kushalp
 * This is a demo class, whose object we want to create
 * using singleton pattern.
 */
class JavaSingletonObject
{

	public JavaSingletonObject()
	{
		System.out.print("Constructor called. ");
	}

	public void printMe()
	{
		System.out.println("I Am JavaSingletonObject.");
	}
}

Java Reflections Tutorial

This tutorial gives an insight on how Java Reflection can be used to load Java classes dynamically at the run time. Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

package com.kushal.utilities;

/**
 * @author Kushal Paudyal
 * 08/05/2008
 * 
 * Simple demonstration of Java Reflection mechanism to
 * instantiate a class, get it's method and call that
 * method with proper parameter passing.
 */
import java.lang.reflect.*;

public class JavaReflectionsDemo {

	public static void main(String args[]) {
		try {
			/*
			 * Step 1 Define a class loader
			 */
			ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
			/*
			 * Step 2: Define a class to be loaded.
			 */
			String classNameToBeLoaded = "com.kushal.utilities.DemoClassToBeLoaded";

			/*
			 * Step 3: Load the class
			 */
			Class myClass = myClassLoader.loadClass(classNameToBeLoaded);

			/*
			 *Step 4: create a new instance of that class
			 */
			Object whatInstance = myClass.newInstance();

			String methodParameter = "ABC";
			/*
			 * Step 5: get the method, with proper parameter signature.
			 * The second parameter is the parameter type.
			 * There can be multiple parameters for the method we are trying to call, 
			 * hence the use of array.
			 */

			Method myMethod = myClass.getMethod("myMethod123",
					new Class[] { String.class });

			/*
			 *Step 6:
			 *Calling the real method. Passing methodParameter as
			 *parameter. You can pass multiple paramters based on 
			 *the signature of the method you are calling. Hence
			 *there is an array. 
			 */
			String returnValue = (String) myMethod.invoke(whatInstance,
					new Object[] { methodParameter });

			System.out.println("The value returned from the method is:"
					+ returnValue);

			/*
			 * Catching Probable Exceptions
			 * You can simply catch the Generic 'Exception' to reduce your coding.		 
			 */
		} catch (ClassNotFoundException e1) {
			System.out.println("EXCEPTION:CLASS NOT FOUND");
		} catch (IllegalAccessException e2) {
			System.out.println("EXCEPTION:ILLEGAL ACCESS");
		} catch (InstantiationException e3) {
			System.out.println("EXCEPTION:INSTANTIATION EXCEPTION");
		} catch (NoSuchMethodException e4) {
			System.out.println("EXCEPTION:NO SUCH METHOD");
		} catch (InvocationTargetException e5) {
			System.out.println("EXCEPTION: INVOCATION TARGET");

		}
	}

}
/**
 * @author Kushal Paudyal
 * 08/05/2008
 * www.sanjaal.com/java
 */

/*
 * This is the demo class that we will use to load and invoke method
 * using Java Reflection.
 */
class DemoClassToBeLoaded {
	public static String myMethod123(String someParam) {
		System.out.println("You Are Calling myMethod()");
		System.out.println("You Passed " + someParam + " as Parameter");

		/*
		 * Just returning the current class name
		 * This is just an example method. 
		 */
		return DemoClassToBeLoaded.class.getName();
	}

}

Calculating Folder Size In Java

The following piece of java code demonstrates how we can calculate the size of a given folder using Java Application. This uses a recursive technique. We start with a root directory, and start listing the files/folder. If a file is found, we calculate its size and sum of total size and also increase the total number of files counted so far, if it is a directory, we further do the recursion.

This program has been fully compiled and tested to find the folder size in Java.

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 30th August 2008
 */
package com.kushal.utilities;

import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class TopLevelFolderSize {

	int totalFolderCount=0;
	int totalFileCount=0;

	public static void main(String args [])
	{
		/**
		 * Define your folder here. This is the folder whose size
		 * statistics you want to find out.
		 */
		String folder = "C:/Users/kushal/Desktop/tempKushal";

		try{
			DecimalFormat fmt =new DecimalFormat("#.##");

			TopLevelFolderSize fg=new TopLevelFolderSize();

			/**Calculating the file size. By default size in long
			 * is returned.
			 */
			long fileSizeByte=fg.getFileSize(new File(folder));

			/**
			 * Formatting the long value to calculate size in
			 * different units KB, MB and GB
			 */
			double fileSizeKB=Double.valueOf(fmt.format(fileSizeByte /1024));
			double fileSizeMB=Double.valueOf(fmt.format(fileSizeByte /(1024*1024)));
			double fileSizeGB=Double.valueOf(fmt.format(fileSizeByte /(1024*1024*1024)));

			/**Printing the statistics**/
			System.out.println("nn##############--Folder Statistics--#################");
			System.out.println("Total Folder Size: ["+fileSizeByte+" Bytes] ntt["
						+fileSizeKB+" KB] ntt["
						+fileSizeMB+" MB] ntt["
						+fileSizeGB+" GB]");
			System.out.println("Total Number of Folders: "+fg.getTotalFolderCount());
			System.out.println("Total Number of Files: "+fg.getTotalFileCount());
			System.out.println("##########--End Of Folder Statistics--##############");

		}catch (Exception e)
		{
			System.out.println("Exception Occurred: "+e.getMessage());
		}
	}

	/**
	 * This is a recursive method.
	 * If file is found, total file size is calculated.
	 * If it is a folder, we recurse further.
	 */
	public long getFileSize(File folder) {
		totalFolderCount++; //Counting the total folders

		System.out.println("Processing " + folder.getName());
		long foldersize = 0;

		File[] filelist = folder.listFiles();
		for (int i = 0; i < filelist.length; i++) {
			if (filelist[i].isDirectory()) {
				foldersize += getFileSize(filelist[i]);
			} else {
				totalFileCount++; //Counting the total files
				foldersize += filelist[i].length();
			}
		}

		return foldersize;
	}

	/**
	 * @return the totalFolderCount
	 */
	public int getTotalFolderCount() {
		return totalFolderCount;
	}

	/**
	 * @return the totalFileCount
	 */
	public int getTotalFileCount() {
		return totalFileCount;
	}

}


———————————————————————
SAMPLE OUTPUT:
———————————————————————
Processing tempKushal
Processing cute pictures
Processing image col
Processing Moline Tornado
Processing send
Processing Party At Prabhakars
Processing images

##############–Folder Statistics–#################
Total Folder Size: [151850658 Bytes]
[148291.0 KB]
[144.0 MB]
[0.0 GB]
Total Number of Folders: 7
Total Number of Files: 154
##########–End Of Folder Statistics–##############