Decorator in JavaScript
The decorator pattern is similar to the proxy pattern in that it’s about “wrapping” an object. However, the decorator pattern is about adding functionality to an object at runtime. Different decorators can be applied to an object to add different functionalities to it.
Implementation
Given the following HttpClient class based on the fetch API, we want to instrument the requests made through this client. HttpClient implements getJson and returns JSON output if the fetch request succeeds:
class HttpClient {
async getJson(url) {
const response = await fetch(url);
if (response.ok) {
return response.json();
}
throw new Error(`Error loading ${url}`);
}
} InstrumentedHttpClient, which is a decorator, might look like the following, where we expose the same getJson method but have the...