For any Java class if we are allowed only one object, such type class called singleton class.
eg-:
Business Delegate
Service Location.
- If several people have the same requirement, then it is not recommanded to create saprate object for every requirement.
- We have to create only one object, we can reuse same object for every similar requirement so that performance and memory utilization will be improved.
How to create our own singleton classes?
Approach 1-:we can create our own singleton class private constructor and private static variable and public factory method.
class Test{
private static Test t=new Test();
private Test(){
}
public static Test getTest(){
return t;
}
}
Test t=Test.getTest();
Test t1=Test.getTest();
Test t3=Test.getTest();
Explanation of above code.
The provided Java code defines a class named `Test` with a private constructor and a static method to retrieve an instance of the `Test` class. Let's break down the code step by step:
1. **Class Declaration**:
class Test {
Here, a class named `Test` is declared.
2. **Static Field**:
private static Test t = new Test();
Inside the class, there's a private static field `t` of type `Test`. This field is initialized with a new instance of the `Test` class. This initialization happens only once when the class is loaded, thanks to the `static` keyword.
3. **Private Constructor**:
private Test() {
}
The class has a private constructor. This means that instances of the `Test` class can only be created from within the class itself.
4. **Static Method**:
public static Test getTest() {
return t;
}
There's a public static method named `getTest()`. This method returns the static instance `t` of the `Test` class.
5. **Creating Instances**:
Test t = Test.getTest();
Test t1 = Test.getTest();
Test t3 = Test.getTest();
Here, three instances of the `Test` class are created using the `getTest()` method. However, due to the static field `t`, all these instances are actually references to the same object created during class initialization. In other words, `t`, `t1`, and `t3` will all point to the same instance of the `Test` class.
class Test{
private static Test t=null;
private Test(){
}
public static Test getTest(){
if(t==null){
t=new Test();
}
return t;
}
}
Test t=Test.getTest();
Test t1=Test.getTest();
Test t3=Test.getTest();