Design Pattern Basic Tutorial

adplus-dvertising
Singleton Pattern
Previous Home Next

The singleton design pattern is work with one and only one object instance, which is merge to the all control from a common place of the object . There are many ways of applying the singleton pattern. Another approach of creating Singleton pattern includes a private constructor and static method in class. Declaration of the private constructor is ensures that the instance will be created only method of the class. The static method is used to sets the variable as Boolean type which is return the true or false. this method indicates the creation of the instance and returns an instance.

Benefit of Singleton Pattern
  1. The Singleton pattern is controlling access to unique instances.
  2. It allows refinement of operations, reduce name space and representations.
  3. It provides more flexibility than class operations, permits a variable number of instances.
Usage of Singleton Pattern

The Singleton pattern is used in which places where only one instance of a class is created. This pattern is used most cases in multi-threaded applications. Singleton patterns used as a global variables because the global variables allow to allocation and initialization whenever required in the class. The Singleton variable do not allow to allocate or initialization global namespace with unnecessary variable.

Example

package r4r;
class Emp {
public static final int companyID = 12345;
public String address;
//...

}
class HEmployee extends Emp {
public double hourlyRate=500;
//....
}
class SEmployee extends Emp {
public double salary=25000;
//...
}

public class singletontests {
public static void main(String[] args) {
Emp Evens = new Emp();
HEmployee Sam = new HEmployee();
SEmployee Suhani = new SEmployee();
System.out.println(Evens.companyID == Sam.companyID); //true
System.out.println(Evens.companyID == Suhani.companyID); //true
System.out.println("Hour Rate is:"+Sam.hourlyRate);
System.out.println("Salary of Suhani:"+Suhani.salary);
}
}
Previous Home Next