Singleton Pattern: Ensure a class only has one instance and
provide a global point of access to it.
Example
ConnectionManager.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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
1 2 3 4 5 6 7 8 | 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
1 2 3 4 5 6 7 8 9 10 | 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