Notice

YouTube.com/BESTTravelers - Visit and SUBSCRIBE to our travel related YouTube Channel named "BEST Travelers"

Thursday, July 14, 2011

Singleton Design Pattern example using Java

Creational Pattern- Ensure a class only has one instance, and provide a global point of access to it.Sometimes we want just a single instance of a class to exist in the system. For example, we want just one window manager. And we want to ensure that additional instances of the class cannot be created.
  • Normally when you have a class and you create many instances of it then you get many objects.
  • But in the case of singleton design pattern we get one instantiated object for many calls of getInstance() method instead of new.
  • Example of Singleton Design pattern is implemented in the following database class. Note that it private constructor. Only getInstance() method is used to create single instance of the class.
public class Database
{
    private static Database singleObject;
    private int record;
    private String name;

    private Database(String n) // Note private
    {
        name = n;
        record = 0;
    }
    public static Database getInstance(String n) //instantiation
    {
        if (singleObject == null){
            singleObject = new Database(n);
        }
        return singleObject;
    }
    public void editRecord(String operation)
    {
        System.out.println("Performing a " + operation + " operation on record " + record + " in database " + name);
    }
    public String getName()
    {
        return name;
    }
}
public class TestSingleton
{
    public static void main(String args[])
    {
        Database database;
        database = Database.getInstance("products");
        System.out.println("This is the " + database.getName() + " databse.");
        database = Database.getInstance("employees");
        System.out.println("This is the " + database.getName() + " databse.");
    }
}

Source:  From lecture notes of Design and Development Open Multi-tier Application 

No comments:

Post a Comment