Elegant patterns in JavaScript
Last Updated :
27 Sep, 2023
In this article, we will learn about Elegant Patterns in JavaScript, the Elegant Patterns in JavaScript explore advanced design patterns that empower developers to create maintainable, scalable, and efficient code, and JavaScript’s flexible nature allows the application of the various patterns that address common software engineering challenges.
There are several methods that can be used to perform Elegant patterns in JavaScript, which are listed below:
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Singleton Pattern
The singleton pattern ensures that a class has only one instance and provides a global point of access to that instance and is valuable for controlling access to a shared resource or maintaining a single configuration object across an application.
Syntax:
class GFG {
constructor() {
if (GFG.instance) {
}
// code
}
}
const A = new GFG();
Example: In this example, we use Singleton pattern implementation. GFG constructor returns existing instance if present, else creates one. A and B reference the same instance. Output: true.
Javascript
class GFG {
constructor() {
if (GFG.instance) {
return GFG.instance;
}
GFG.instance = this ;
}
}
const A = new GFG();
const B = new GFG();
console.log(A === B);
|
Approach 2: Observer Pattern
The observer model facilitates communication between objects and here an object maintains a list of its dependents and notifies them of the any state changes.
Syntax:
class GFG {
constructor() {
}
addObserver(observer) {
}
removeObserver(observer) {
this.obs = this.obs.filter(obs =>
obs !== observer);
}
notify(data) {
this.obs.forEach(observer =>
observer.update(data));
}
// code
}
class Observer {
constructor(name) {
this.name = name;
}
}
Example: In this example, Class GFG manages observers, notifies them of data changes. Observer receives updates. Instances added, notified. Output: Observers respond to ‘Update 01’.
Javascript
class GFG {
constructor() {
this .obs = [];
}
addObserver(observer) {
this .obs.push(observer);
}
removeObserver(observer) {
this .obs = this .obs.filter(obs =>
obs !== observer);
}
notify(data) {
this .obs.forEach(observer =>
observer.update(data));
}
}
class Observer {
constructor(name) {
this .name = name;
}
update(data) {
console.log(`${ this .name}
received the data: ${data}`);
}
}
const subject = new GFG();
const observer1 = new Observer( 'Observer 01' );
const observer2 = new Observer( 'Observer 02' );
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notify( 'Update 01' );
|
Output
Observer 01
received the data: Update 01
Observer 02
received the data: Update 01
Share your thoughts in the comments
Please Login to comment...