Applying Behavioral Patterns in JavaScript Scenarios

Applying Behavioral Patterns in Real-World Scenarios

We are advancing through our journey of building various real-world applications. We have explored the Command, Observer, and Strategy patterns in the previous units. In this unit, we will integrate all three behavioral patterns into different scenarios to solve real-world problems.

Before diving into the coding exercise, let's have a quick recap of what each pattern does. The Command pattern encapsulates a request as an object, allowing clients to parameterize and queue requests. The Observer pattern defines a one-to-many dependency between objects, ensuring that when one object changes state, all its dependents are notified and updated automatically. The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Clients can choose the algorithm to use at runtime.

Let us consider one scenario of using the Command and Observer patterns together to build a chat application.

Building a Chat Application

The Command pattern encapsulates a request as an object, supporting the parameterization of clients with different requests and enabling undoable operations. Here’s a quick sample demonstrating how to encapsulate the action of showing a message in the chat room:

We define a base Command class with an execute method that needs to be implemented by subclasses. This serves as the blueprint for all command objects, ensuring they adhere to a common execution interface.

JavaScript
class Command {
    execute() {
        throw "Execute method must be implemented";
    }
}

Next, we define a ChatRoom class with a method to display and propagate messages. The sendMessage function in the ChatRoom class will be defined further down below.

JavaScript
class ChatRoom {
    showMessage(message) {
        console.log(`Message: ${message}`);
    }
}

The ChatCommand class inherits from Command and encapsulates the action of showing a message. When creating a ChatCommand, you set the message and the chat room where the message will be displayed, then execute this command to display the message.

Now, we integrate the Observer pattern to enable our chat application to notify users about incoming messages. Each User instance represents an observer that can receive messages, while the ChatRoom acts as the subject that notifies its users.

JavaScript
class ChatCommand extends Command {
    constructor(chatRoom, message) {
        super();
        this.chatRoom = chatRoom;
        this.message = message;
    }

    execute() {
        this.chatRoom.showMessage(this.message);
        this.chatRoom.sendMessage(this.message);
    }
}

We define a User class where each user can receive and print messages. This will allow users to get real-time updates from the chat room.

JavaScript
class User {
    constructor(name) {
        this.name = name;
    }

    receiveMessage(message) {
        console.log(`${this.name} received message: ${message}`);
    }
}

Here, the ChatRoom class is enhanced to hold a list of users and send messages to all users by iterating through the list, simulating the observer notification. Adding the Observer pattern ensures that new messages are immediately communicated to all users.

JavaScript
class ChatRoom {
    constructor() {
        this.users = [];
    }

    addUser(user) {
        this.users.push(user);
    }
        
    showMessage(message) {
        console.log(`Message: ${message}`);
    }

    sendMessage(message) {
        this.users.forEach(user => user.receiveMessage(message));
    }
}

Now, we will combine both the Command and Observer patterns to create a functional chat application. You will use commands to handle user inputs and observers to manage message broadcasting. This integration increases the modularity and clarity of the application structure, making it easier to maintain and extend.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal