Java Singleton Class

 SINGLETON CLASS:

Define a class that has only one instance and provides global access to it.

 How to create a singleton class:-

Make a private constructor.

A static member should be there.

 


 Example 01:

class ABC{

static ABC obj = null; //static member

private ABC(){}  //private constructor

//the following instructions method will hel[ us to create an object instance.

Public static ABC getInstance(){

if obj==null;

 obj= new ABC();

else

   return obj;

}

//This will help to create an instance.

//For calling in the main() function.

Classname obj = classname.getInstance();

obj.methodname;

 

ABC in = ABC.getInstance();

in.display();

Example 02:

package Classess;


public class singletonClass {



private static singletonClass instance;


// Private constructor to prevent instantiation from other classes

private singletonClass() {

}


// Public method to provide access to the Singleton instance

public static singletonClass getInstance() {

if (instance == null) {

instance = new singletonClass();

}

return instance;

}


public double calculateTriangleArea(double base, double height) {

return 0.5 * base * height;

}


public double calculateSquareArea(double side) {

return side * side;

}


public static void main(String[] args) {

singletonClass calculator = singletonClass.getInstance();


double triangleArea = calculator.calculateTriangleArea(5.0, 4.0);

System.out.println("Area of the triangle: " + triangleArea);


double squareArea = calculator.calculateSquareArea(6.0);

System.out.println("Area of the square: " + squareArea);

}



}




Post a Comment

0 Comments