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.");
	}
}

Creating Category Chart Using JFreeChart

In this basic tutorial, I am walking through how to create category chart using JFreeChart. The program uses the following two jar files, and they come with the JFreeChart itself. You can download JFreeChart at their official website www.jfreechart.org

  • jcommon-1.0.15.jar
  • jfreechart-1.0.12.jar

The program also demonstrates how easily you can save a generated chart to your computer using the Charts Utilities from JFreeChart

package com.kushal.utilities;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

public class CategoryChartDemo {

	public void createCategoryChart()
	{

		DefaultCategoryDataset  categoryDataset = new DefaultCategoryDataset();

		//Enrollment in Bachelors level
		categoryDataset.setValue(2003, "Bachelors", "2005");
		categoryDataset.setValue(1350, "Bachelors", "2006");
		categoryDataset.setValue(2408, "Bachelors", "2007");
		categoryDataset.setValue(2607, "Bachelors","2008");

		//Enrollment in Masters level
		categoryDataset.setValue(985, "Masters", "2005");
		categoryDataset.setValue(1400, "Masters", "2006");
		categoryDataset.setValue(1634, "Masters", "2007");
		categoryDataset.setValue(978, "Masters", "2008");

		//Enrollment in PhD level
		categoryDataset.setValue(356, "PhD", "2005");
		categoryDataset.setValue(390, "PhD", "2006");
		categoryDataset.setValue(350, "PhD", "2007");
		categoryDataset.setValue(687, "PhD", "2008");

		JFreeChart chart = ChartFactory.createBarChart3D
				     ("Program Enrollment (c) www.sanjaal.com", // Title
				      "Year",              // X-Axis label
				      "Number of Students",// Y-Axis label
				      categoryDataset,         // Dataset
				      PlotOrientation.VERTICAL,
				      true,                     // Show legend
				      true,
				      false
				     );

		saveChart(chart);
	}

	public void saveChart(JFreeChart chart)
	{
		String fileName="C:/Users/kushal/Desktop/myCategoryChart.jpg";
		try {
			/**
			 * This utility saves the JFreeChart as a JPEG
			 * First Parameter: FileName
			 * Second Parameter: Chart To Save
			 * Third Parameter: Height Of Picture
			 * Fourth Parameter: Width Of Picture
			 */
	    ChartUtilities.saveChartAsJPEG(new File(fileName), chart, 800, 600);
	} catch (IOException e) {
		e.printStackTrace();
	    System.err.println("Problem occurred creating chart.");
	}
	}
	public static void main(String args [])
	{
		new CategoryChartDemo().createCategoryChart();

	}

}


The following is the output when you run this program: