Search This Blog

2023/08/30

Decorator Design Pattern

 // Component Interface

class Text {
constructor(content) {
this.content = content;
}

format() {
return this.content;
}
}

// Concrete Component
class PlainText extends Text {
constructor(content) {
super(content);
}
}

// Decorator
class TextDecorator extends Text {
constructor(text) {
super();
this.text = text;
}

format() {
return this.text.format();
}
}

// Concrete Decorator
class BoldDecorator extends TextDecorator {
constructor(text) {
super(text);
}

format() {
return `<b>${this.text.format()}</b>`;
}
}

class ItalicDecorator extends TextDecorator {
constructor(text) {
super(text);
}

format() {
return `<i>${this.text.format()}</i>`;
}
}

// Usage
const plainText = new PlainText("Hello, world!");

const boldText = new BoldDecorator(plainText);
const italicBoldText = new ItalicDecorator(boldText);

console.log(plainText.format()); // Output: Hello, world!
console.log(boldText.format()); // Output: <b>Hello, world!</b>
console.log(italicBoldText.format()); // Output: <i><b>Hello, world!</b></i>

The Decorator pattern here is used to apply
formatting (bold and italic) to text content
in a flexible and extensible way. It demonstrates
how decorators can be stacked to create more complex
behaviors while keeping individual decorators reusable.

No comments:

Post a Comment