• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

CH-04 : The Singleton Paradox — Jai & Veeru vs. The Multiverse of Objects

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Jai and Veeru were sipping chai on their terrace when Veeru suddenly blurted out, “Jai, our app has a problem!”

Jai, halfway through a biscuit, raised an eyebrow. “What now? Did you time-travel and forget your phone again?”

Veeru shook his head. “Worse. Our app is creating too many objects! The memory usage is skyrocketing!”

Jai sighed. “Ah, the Singleton problem. We need only one instance of an object, but Java keeps making more, wasting resources.”

Veeru scratched his head. “So how do we fix it?”

Jai leaned forward, a mischievous smile forming. “We use Java 21’s Record Patterns & Sealed Classes!”

Veeru blinked. “Sounds fancy. Explain.”

The Problem: Too Many Instances


Veeru had written this code for a Logger class:


public class Logger {
public Logger() { System.out.println("New Logger Created!"); }
}

And every time he called new Logger(), it created a new instance!

Veeru frowned. “But I only need one logger. Not a thousand!”

Jai smirked. “That’s where Singleton Pattern comes in!”

The Fix: Singleton with Sealed Classes


Jai rewrote the Logger class using Java 21’s Sealed Classes:


public sealed class Logger permits OnlyOne {
private Logger() {} // Private Constructor
private static final Logger instance = new Logger();
public static Logger getInstance() { return instance; }
}

final class OnlyOne extends Logger {} // Prevents more instances

Veeru’s eyes widened. “Wait… so now, even if someone tries to extend Logger, Java won’t allow it?"

Jai nodded. Yes! Sealed classes restrict inheritance, enforcing one true instance!"

Veeru clapped his hands. “Jai, you’re a genius!”

Record Patterns: The New Magic Trick


Veeru frowned again. “Okay, Singleton is solved. But what if we have too many duplicate objects, like users logging in with the same details?”

Jai chuckled. “That’s where Record Patterns help. Instead of manually checking fields, Java 21 does it for us!”

Instead of writing this old, tedious way:


record User(String name, String role) {}

User u = new User("Veeru", "Admin");
if (u.name().equals("Veeru") && u.role().equals("Admin")) {
System.out.println("Welcome, Admin!");
}

Jai showed the modern approach:


record User(String name, String role) {}

static void checkUser(User u) {
if (u instanceof User("Veeru", "Admin")) {
System.out.println("Welcome, Admin!");
}
}

Veeru was stunned. “That’s so much cleaner! No more repetitive .equals() calls?"

Jai grinned. “Yup! Java 21 makes code smarter and easier to read.”

The Real Paradox…


Just as Jai and Veeru were celebrating their victory, Veeru’s phone beeped. It was an error message from their server.

“Warning: Multiple instances detected. Memory overload imminent!”

Veeru gulped. “Jai… didn’t we just fix this?”

Jai stared at the screen, confused. Yes… which means something — or someone — is breaking the Singleton rule…”

They exchanged a nervous glance.

“Could it be… a rogue object?” Veeru whispered.

Jai’s eyes narrowed. “Only one way to find out.”

? To be continued… ?

?Key Takeaways from This Chapter


✔ Sealed Classes — Prevent unnecessary object creation.
✔ Singleton with Permits — Restrict inheritance for a true singleton pattern.
✔ Record Patterns — Cleaner, more readable pattern matching.
✔ Better Performance — Java 21 optimizes memory and CPU usage.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу