- 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.
{
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