🎁Decorator Pattern – Overview
🧠 Concept
🧱 Key Roles
Role
Description
💻 Java Example – UI Example (TextField with Scrollbars & Borders)
// ----- Component -----
interface UIComponent {
void render();
}
// ----- Concrete Component -----
class TextField implements UIComponent {
public void render() {
System.out.println("Rendering basic text field");
}
}
// ----- Base Decorator -----
abstract class UIComponentDecorator implements UIComponent {
protected UIComponent component;
public UIComponentDecorator(UIComponent component) {
this.component = component;
}
public void render() {
component.render(); // delegate to wrapped component
}
}
// ----- Concrete Decorators -----
class BorderDecorator extends UIComponentDecorator {
public BorderDecorator(UIComponent component) {
super(component);
}
public void render() {
super.render();
System.out.println("→ Adding border decoration");
}
}
class ScrollbarDecorator extends UIComponentDecorator {
public ScrollbarDecorator(UIComponent component) {
super(component);
}
public void render() {
super.render();
System.out.println("→ Adding scrollbar decoration");
}
}
// ----- Client -----
public class Main {
public static void main(String[] args) {
// Start with a plain text field
UIComponent textField = new TextField();
// Decorate it with scrollbar
UIComponent scrollable = new ScrollbarDecorator(textField);
// Further decorate with border
UIComponent borderedScrollable = new BorderDecorator(scrollable);
borderedScrollable.render();
}
}🧠 Flow Summary
Step
Action
Result
🪜 Summary
🧾 Real-world Analogy
🧭 TL;DR
Last updated