Register now or log in to join your professional community.
we can create the Singleton class by using private access modified with its constructor declaration
Singleton class have private constructor and one private refrence to the current objects, also have getInstance function return that private refrence to each point you called it
Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as private, so that you can restrict the creation of the object. Provide a static method to get instance of the object, wherein you can handle the object creation inside the class only
First need to create private constructot inside a class and will create one static method which should return its on class type, inside method we will using if condition and will check,if it is new instance then will allow to create instance otherwise will return the last.
To design a singleton class:
To design a singleton class:
Make a constructor as Private
write a static method
//Given name to your class, by suffxing Single, it indicates that it is a single ton //class
//If we cannot implement, then end user can clone the declared object.
public class MyXXXSingleton implements Cloneable {
private static MyObject obj=null;
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Singleton Class does not support this method.");
}
private MyXXXSingletons(){
//Do any initializaions if necessary
}
public MyXXXSingleton static getInstance(){
if(obj==null){
obj= new MyObject();
returb obj;
}else{
return obj;
}
}
}
Code Example of Create own Singleton Class in java:
class Test {
private static Test t = null;
// if constructor is public then it is possible to create many object
private Test() {}
public static Test getTest(){
if(t == null){
new Test();
}
return t;
}
}
// Now if we just call Test t1 = Test.getTest() method, we can get benefit of singleton class object, for re-usability, save memory and incise memory performance.