Skip to main content

Singleton class

 For any Java class if we are allowed only one object, such type class called singleton class.

eg-:

Runtime
Business Delegate
Service Location.

Advantage of singleton class-:
  • 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.
This is the central idea are singleton classes.

eg-:
Runtime r1=Runtime.getRuntime();
Runtime r2=Runtime.getRuntime();
.
.
.
.
Runtime r100000=Runtime.getRuntime();



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.





Approach 2-:

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();



The code you provided is an example of a design pattern called the Singleton Pattern. In this pattern, a class ensures that it has only one instance and provides a global point of access to that instance. Let's break down the code step by step:

1. **Class Definition:**
   
   
   class Test {
  
   This code defines a class named `Test`.

2. **Static Variable:**
   
  
   private static Test t = null;
  
   This line declares a private static variable `t` of type `Test`. Static means there is only one instance of this variable shared among all instances of the `Test` class.

3. **Private Constructor:**
   

   private Test() {
   }
 
   This is a private constructor for the `Test` class. It means that no objects of this class can be created from outside the class.

4. **Static Method `getTest()`:**
   
 
   public static Test getTest() {
       if (t == null) {
           t = new Test();
       }
       return t;
   }

   This is a public static method called `getTest()`. It is used to get the single instance of the `Test` class. Here's how it works:
   
   - If the `t` variable is `null` (meaning no instance of `Test` has been created yet), it creates a new instance of the `Test` class and assigns it to `t`.
   - It then returns the instance stored in `t`.
   - If an instance of `Test` already exists (i.e., `t` is not `null`), it simply returns the existing instance. This ensures that only one instance of `Test` is created and reused.

5. **Using the Singleton:**
   

   Test t = Test.getTest();
   Test t1 = Test.getTest();
   Test t3 = Test.getTest();
 
   These lines demonstrate how to use the singleton pattern to get instances of the `Test` class. Since `getTest()` ensures that only one instance is created, `t`, `t1`, and `t3` will all refer to the same `Test` instance.

In summary, this code defines a `Test` class that implements the Singleton Pattern. It ensures that there is only one instance of the `Test` class, and you can obtain that instance using the `getTest()` method. This is commonly used in scenarios where you need a single global point of control or access to a particular resource or configuration.

Popular posts from this blog

Java

Codes With Java — Basics Codes With Java Java tutorials & fundamentals About Contact Privacy Basic Fundamentals Java source file structure Import Statement Static Import Packages Data Type Variables Final Variable Declaration and Access Modifier Inner classes applicable modifiers Static Modifier Synchronized Native Transient Volatile Interface Introduction Interface Declaration and Implementation Interface methods and variables Naming Conflicts Interface Marker interface and Ad...

Short Circuite Operators part 4

                                                             Short Circuit Operators In  Java logical operators , if the evaluation of a logical expression exits in between before complete evaluation, then it is known as  Short-circuit . A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to efficient processing. 1-: AND(&&) 2-:OR(||) these are exactly same as bitwise operators (&,|) except the following differences. Single Short Circuit Operator(&,|) Both arguments Should be evaluated always. relatively performance is low. Applicable for both boolean and Integral types. Double Short Circuit Operator(...

Operators & Assignment part 3

                                                                                       Operators & Assignment 1-:instanceof Operators 2-:Bitwise Operators                                                                        instanceof Operators we can use instanceof operator to check whether the given object is of a particular type are not. Example-: /* list is a collection of objects. List l=new List(); l.add(Customer); l.add(Student); l.add(Test); Object o=l.get(...