TIL Adapters, proxies, and decorators
POSTED ON:
TAGS: oop
Differences of Adapters, Proxies, and Decorators #
An adapter provides a different interface to the object it adapts.
With the Adapter pattern, it involves creating an intermediary object (the adapter) to translates the interface of one object so that it can be used by another object.
A Proxy provides the same interface as its subject.
The purpose of the Proxy pattern is to provide a placeholder for another object to control and manage access to it. The pattern acts as a wrapper that allows you to perform something either before or after the request gets through to the original object.
// The primary class
class RealImage {
constructor(fileName) {
this.fileName = fileName;
this.loadFromDisk();
}
display() {
console.log(`Displaying ${this.fileName}`);
}
loadFromDisk() {
console.log(`Loading ${this.fileName}`);
}
}
// We are wrapping the primary class around this
class ImageProxy {
constructor(fileName) {
this.fileName = fileName;
}
// This controls the display
display() {
if (!this.realImage) {
this.realImage = new RealImage(this.fileName);
}
this.realImage.display();
}
}
const image1 = new ImageProxy('image1.jpg');
image1.display(); // "Loading image1.jpg" "Displaying image1.jpg"
image1.display(); // "Displaying image1.jpg" (no loading because it was already loaded)
Decorator adds one or more responsibilities to an object.
It wraps around a feature.
// The original class
class Text {
constructor(content) {
this.content = content;
}
print() {
console.log(this.content);
}
}
// We want to 'DECORATE' this class
class BoldDecorator {
constructor(text) {
this.text = text;
}
print() {
console.log(`<b>${this.text.content}</b>`);
}
}
const plainText = new Text('This is plain text.');
const boldText = new BoldDecorator(plainText);
boldText.print(); // "<b>This is plain text.</b>"
Difference between Proxies and Decorators #
The Proxy pattern creates a wrapper object around an object to control access to it, whereas the Decorator pattern creates a wrapper object to add new behavior to the original object.
In other words, the Proxy provides an object that acts as a substitute for the original object, whereas the Decorator adds new functionality to the original object without changing its interface.
Related TILs
Tagged: oop