Friday, April 22, 2011

Singleton Class in Java

     

           A Singleton class is used when you wish to restrict instantiation of a class to only one object.
           Suppose we have to retain the values of the Variables and want to restrict the creation of more than objects then we can use Singleton pattern.

Step 1: Create a Class which extends Observable, as i shown below

public class Viewmore extends Observable {


// create the Instance of Viewmore as static ,since make that object as class Variable

private static Viewmore instance;

private Viewmore() {
/** Default Constructor(Empty Constructor) */
}

// Create a method , which checks whether the instances is already created or not

public static Viewmore getInstance() {
if (instance == null) {
instance = new Viewmore();
}
return instance;
}

Step 2: Cerate the Singleton Object as i Shown below

class Samp {

// Create the Instance of Singleton 

Viewmore vm = Viewmore.getInstance();

}
 





No comments:

Post a Comment

Notification in Android Using AlarmManager, BoradCastReceiver & Services

    Our aim is to show notification message to user in a specific time.     Say For example , I have planned to show Notification ...