Singleton Pattern

Singleton Pattern Java Design Pattern Tutorial
Singleton Pattern: Ensure a class only has one instance and provide a global point of access to it.

Example

ConnectionManager.java
package com.singletonpattern.example;

public class ConnectionManager {
 
 private static ConnectionManager connectionManager = new ConnectionManager();

 private ConnectionManager() {
  System.out.println("Database Connection set successfully");
 }

 public static ConnectionManager getConnectionInstance() {
  return connectionManager;
 }
 
}
EntityManger.java
package com.singletonpattern.example;

public class EntityManger { 
 
 public void getItemDetails(ConnectionManager connectionManager){
  System.out.println("Now performing  database select operation using connectionManager instance");
 }
}
ConnectionManagerTestDrive.java
package com.singletonpattern.example;

public class ConnectionManagerTestDrive {
 public static void main(String[] args) {
  //Using single instance of Connection Manager
  ConnectionManager dbConnection = ConnectionManager.getConnectionInstance();
  EntityManger entityManger = new EntityManger();
  entityManger.getItemDetails(dbConnection);
 }
}




Home

No comments:

Post a Comment