Jay Desai
DJay's Tech Diary

Follow

DJay's Tech Diary

Follow
Advanced JavaScript Design Patterns: Part 2

Advanced JavaScript Design Patterns: Part 2

The Constructor Pattern

Jay Desai's photo
Jay Desai
ยทJan 23, 2023ยท

2 min read

Play this article

Object-oriented programming is a popular programming paradigm that allows developers to model real-world objects and their interactions in code. One of the key concepts in object-oriented programming is the use of classes, which act as templates for creating objects with specific properties and methods.

The constructor pattern is a design pattern used in object-oriented programming to create objects with a specific set of properties and methods. In this blog post, we will take a closer look at the constructor pattern and how it can be used to create robust, reusable code.

A constructor is a special method that is automatically called when an object is created from a class. The constructor function is typically defined using the keyword "constructor" and can take in parameters to set the initial values of the object's properties. Once the constructor function is defined, it can be used to create new instances of the object using the "new" keyword.

Constructor Pattern Example

class EventEmitter {
    private events: { [key: string]: Array<(data: any) => void> } = {};

    on(eventName: string, callback: (data: any) => void) {
        if (!this.events[eventName]) {
            this.events[eventName] = [];
        }
        this.events[eventName].push(callback);
    }

    emit(eventName: string, data: any) {
        if (this.events[eventName]) {
            this.events[eventName].forEach(callback => callback(data));
        }
    }

    off(eventName: string, callback: (data: any) => void) {
        if (this.events[eventName]) {
            this.events[eventName] = this.events[eventName].filter(cb => cb !== callback);
        }
    }
}

class User extends EventEmitter {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        super();
        this.name = name;
        this.age = age;
    }

    login() {
        this.emit("login", { name: this.name });
    }

    logout() {
        this.emit("logout", { name: this.name });
    }
}

let user = new User("John Doe", 30);
user.on("login", data => console.log(`${data.name} has logged in.`));
user.on("logout", data => console.log(`${data.name} has logged out.`));

user.login(); // "John Doe has logged in."
user.logout(); // "John Doe has logged out."

In this example, the EventEmitter class is a constructor that creates a custom event-driven system. It has methods for registering event listeners, emitting events, and removing event listeners. The User class extends the EventEmitter class and has its own properties and methods. The User class is using the EventEmitter to emit events when the user logs in and logs out. The EventEmitter class is handling the listeners and emitting the events. This example shows how the constructor pattern can be used to create complex, reusable code that can be used across multiple classes.

Conclusion

The Constructor pattern is a design pattern that allows for creating objects with specific properties and methods and is commonly used to create reusable and maintainable code.

Did you find this article valuable?

Support Jay Desai by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this