Single tone classes. - rahul00773/JavaConcepts GitHub Wiki

For any java class if we are allowed to create only object such type of class is called singleton class. Example: RunTime, BusinessDelegate, SeviceLocator, etc

Advantage of SingleTone Class:

If several people have the same requirement then it is not recommended to create a separate object for every requirement. We have to create only one object and we can reuse the same object for a similar requirements. So that performance and memory utilization will be improved. This is the central idea of single-tone classes.

How to create our own SingleTone classes:

We can create Our own singleton classes for this we have to use private constructor and private static variable and public factory Method.

Approach 1:

class Test{

private static Test t = new Test();

private Test(){

}

public static Test getTest(){

return t; }

}

Note: Runtime class is internally implemented by using this approach.

Approach2:

class Test{

private static Test t = null;

private Test(){

}

public static Test getTest(){

if(t==null{

Test t = new Test(); } return t; }

}

At any point of time for test class we can create only one object hence test class is singleTone class.

Class is not final but we are not allowed to create child classes how it is possilbe:

By declaring every constructor as private we can restrict child class creation.

class P{

private P{

}

}

For the above class, it is impossible to create a child class