How to use the Decorator Pattern in Java for flexibility

Decorator Pattern in Java Sometimes you want to add features to an object. You do not want to modify the original class. You do not want to create many subclasses. The Decorator Pattern solves this. Use it when you want to extend behavior at runtime. Example interface Notifier { void send(String message); } class BasicNotifier implements Notifier { public void send(String message) { System.out.println("Sending notification: " + message); } } class EmailDecorator implements Notifier { private Notifier notifier; public EmailDecorator(Notifier notifier) { this.notifier = notifier; } public void send(String message) { notifier.send(message); System.out.println("Email sent"); } } class SmsDecorator implements Notifier { private Notifier notifier; public SmsDecorator(Notifier notifier) { this.notifier = notifier; } public void send(String message) { notifier.send(message); System.out.println("SMS sent"); } } Use it like this Notifier notifier = new SmsDecorator(new EmailDecorator(new BasicNotifier())); notifier.send("User registered"); Result • Sends base notification • Sends email • Sends SMS Clear benefits • Add features without touching the original class • No subclass explosion • Flexible and simple When to use • When you need optional features • When you want to avoid large inheritance hierarchies Takeaway The Decorator Pattern gives you flexibility. You attach new behavior without breaking existing code. #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment

To view or add a comment, sign in

Explore content categories