Implementing Singleton Design Pattern in Java

📚 𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐒𝐢𝐧𝐠𝐥𝐞𝐭𝐨𝐧 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 in Java What is Singleton? Singleton ensures: ▪️ Only one object is created ▪️ Same instance is reused across the application Let’s break it down with a simple example 𝐩𝐚𝐜𝐤𝐚𝐠𝐞 𝐜𝐨𝐦.𝐦𝐨𝐝𝐞𝐥; 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 { 𝐩𝐫𝐢𝐯𝐚𝐭𝐞 𝐢𝐧𝐭 𝐞𝐦𝐩𝐈𝐝; 𝐩𝐫𝐢𝐯𝐚𝐭𝐞 𝐬𝐭𝐚𝐭𝐢𝐜 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 𝐞𝐦𝐩; 𝐩𝐫𝐢𝐯𝐚𝐭𝐞 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞() { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 𝐨𝐛𝐣𝐞𝐜𝐭 𝐜𝐫𝐞𝐚𝐭𝐞𝐝"); } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 𝐠𝐞𝐭𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞𝐈𝐧𝐬𝐭𝐚𝐧𝐜𝐞() { 𝐢𝐟 (𝐞𝐦𝐩 == 𝐧𝐮𝐥𝐥) { 𝐞𝐦𝐩 = 𝐧𝐞𝐰 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞(); // 𝐎𝐛𝐣𝐞𝐜𝐭 𝐜𝐫𝐞𝐚𝐭𝐞𝐝 𝐨𝐧𝐥𝐲 𝐨𝐧𝐜𝐞 } 𝐫𝐞𝐭𝐮𝐫𝐧 𝐞𝐦𝐩; } } 𝐩𝐚𝐜𝐤𝐚𝐠𝐞 𝐜𝐨𝐦.𝐦𝐨𝐝𝐞𝐥; 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐓𝐞𝐬𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 𝐞𝐦𝐩𝐥𝐨𝐲𝐞𝐞 = 𝐠𝐞𝐭𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞(); 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧(𝐞𝐦𝐩𝐥𝐨𝐲𝐞𝐞.𝐡𝐚𝐬𝐡𝐂𝐨𝐝𝐞()); 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 𝐞𝐦𝐩𝐥𝐨𝐲𝐞𝐞𝟏 = 𝐠𝐞𝐭𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞(); 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧(𝐞𝐦𝐩𝐥𝐨𝐲𝐞𝐞𝟏.𝐡𝐚𝐬𝐡𝐂𝐨𝐝𝐞()); 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞 𝐞𝐦𝐩𝐥𝐨𝐲𝐞𝐞𝟒 = 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞.𝐠𝐞𝐭𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞𝐈𝐧𝐬𝐭𝐚𝐧𝐜𝐞(); 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧(𝐞𝐦𝐩𝐥𝐨𝐲𝐞𝐞𝟒.𝐡𝐚𝐬𝐡𝐂𝐨𝐝𝐞()); } 𝗽𝘂𝗯𝗹𝗶𝗰 𝘀𝘁𝗮𝘁𝗶𝗰 𝗘𝗺𝗽𝗹𝗼𝘆𝗲𝗲 𝗴𝗲𝘁𝗘𝗺𝗽𝗹𝗼𝘆𝗲𝗲() { 𝗿𝗲𝘁𝘂𝗿𝗻 𝗘𝗺𝗽𝗹𝗼𝘆𝗲𝗲.𝗴𝗲𝘁𝗘𝗺𝗽𝗹𝗼𝘆𝗲𝗲𝗜𝗻𝘀𝘁𝗮𝗻𝗰𝗲(); } } Output : 𝟭𝟯𝟰𝟮𝟰𝟰𝟯𝟮𝟳𝟲 𝟭𝟯𝟰𝟮𝟰𝟰𝟯𝟮𝟳𝟲 𝟭𝟯𝟰𝟮𝟰𝟰𝟯𝟮𝟳𝟲 In this code, we are implementing the Singleton Design Pattern. ➡️ Only one object of "Employee" class is created ➡️ Every time we call "getEmployeeInstance()", we get the same object ⚙️ 𝐇𝐨𝐰 𝐒𝐢𝐧𝐠𝐥𝐞𝐭𝐨𝐧 𝐢𝐬 𝐚𝐜𝐡𝐢𝐞𝐯𝐞𝐝? private static Employee emp; public static Employee getEmployeeInstance() { if(emp == null) { emp = new Employee(); } return emp; } ⏳ First call → object created ⌛Next calls → same object returned 🔍 𝐊𝐞𝐲 𝐎𝐛𝐬𝐞𝐫𝐯𝐚𝐭𝐢𝐨𝐧𝐬 𝐟𝐫𝐨𝐦 𝐎𝐮𝐭𝐩𝐮𝐭 All hashcodes will be same Meaning: all references point to one single object in memory 🔐 Why is the constructor "𝐩𝐫𝐢𝐯𝐚𝐭𝐞"? This is the most important part ➡️ 𝐩𝐫𝐢𝐯𝐚𝐭𝐞 𝐄𝐦𝐩𝐥𝐨𝐲𝐞𝐞() { } 📝 Prevents object creation from outside the class ❌ "new Employee()" is NOT allowed outside 🗒️ Object can only be created inside the class itself ➡️ This ensures: ▪️ No multiple objects ▪️ Full control over object creation 🗒️ Singleton ensures single object creation ▪️ "private constructor" enforces control ▪️ Widely used in real-world frameworks like Spring #Java #OOP #DesignPatterns #SingletonPattern #SpringFramework #BackendDevelopment #Programming #InterviewPrep #LearnBySharing 🚀

To view or add a comment, sign in

Explore content categories