Implementation of Observer Method
Implementing the Observer Pattern with a Weather Monitoring System Example:
Javascript
// Define a WeatherStation class class WeatherStation { constructor() { // Initialize an empty array to hold observers this .observers = []; // Initialize the temperature to 0 this .temperature = 0; } // Method to add an observer to the list addObserver(observer) { this .observers.push(observer); } // Method to remove an observer from the list removeObserver(observer) { this .observers = this .observers.filter(obs => obs !== observer); } // Method to set the temperature and notify observers setTemperature(temperature) { this .temperature = temperature; this .notifyObservers(); } // Method to notify all observers about the temperature change notifyObservers() { this .observers.forEach(observer => { // Call the update method on each observer observer.update( this .temperature); }); } } // Define a DisplayDevice class class DisplayDevice { constructor(name) { // Store the name of the display device this .name = name; } // Method called when the display is updated with temperature update(temperature) { // Log a message indicating the name of the display and the temperature console.log(`${ this .name} Display: Temperature is ${temperature}°C`); } } // Create an instance of the WeatherStation class const weatherStation = new WeatherStation(); // Create two instances of the DisplayDevice class with different names const displayDevice1 = new DisplayDevice( "Display 1" ); const displayDevice2 = new DisplayDevice( "Display 2" ); // Add both display devices as observers to the weather station weatherStation.addObserver(displayDevice1); weatherStation.addObserver(displayDevice2); // Simulate a change in temperature by setting it to 25°C weatherStation.setTemperature(25); // Simulate another change in temperature by setting it to 30°C weatherStation.setTemperature(30); |
Display 1 Display: Temperature is 25°C Display 2 Display: Temperature is 25°C Display 1 Display: Temperature is 30°C Display 2 Display: Temperature is 30°C
In the output, you can see that the two display devices, “Display 1” and “Display 2,” receive and display the temperature updates when the temperature changes. The first update sets the temperature to 25°C, and the second update changes it to 30°C. Both display devices log the updated temperature values to the console.
In the above Code,
- WeatherStation Class: This class represents a weather station and is responsible for managing temperature data and notifying observers when the temperature changes.
- Constructor: The WeatherStation class begins with a constructor function. It initializes two important properties:
- Observers: An empty array to hold all the observers (in this case, the display devices).
- Temperature: An initial temperature value set to 0°C.
- AddObserver Method: The addObserver method allows observers to subscribe to the weather station. It takes an observer parameter (in this context, a display device) and adds it to the list of observers.
- RemoveObserver Method: The removeObserver method enables the removal of observers from the list. It takes an observer as a parameter and filters out the matching observer from the list of observers.
- SetTemperature Method: The setTemperature method is used to update the temperature data. It takes a temperature parameter and sets the temperature property to the new value. After updating the temperature, it calls notifyObservers().
- NotifyObservers Method: The notifyObservers method iterates through the list of observers (display devices) and informs them of the temperature change. For each observer, it calls the update method and passes the current temperature as an argument.
- DisplayDevice Class: This class represents a display device, such as a digital thermometer, and is designed to respond to temperature updates.
- Constructor: The DisplayDevice class begins with its constructor function, which takes a name parameter. This parameter represents the name or identifier of the display device.
- update Method: The update method is called when the display device receives a temperature update from the weather station. It logs a message to the console, indicating the device’s name and the current temperature in degrees Celsius.
- Creating Instances: Instances of the WeatherStation and DisplayDevice classes are created. Additionally, two display devices are instantiated with names, ‘Display 1’ and ‘Display 2’.
- Adding Observers: Both display devices are added as observers to the weather station using the addObserver method. This means they will be notified when the temperature changes.
- Simulating Temperature Changes: To simulate temperature changes, the setTemperature method of the weather station is called twice. First, it sets the temperature to 25°C, and then it updates it to 30°C. Each time the temperature changes, the observers are notified, and they log the updated temperature to the console.
Observer Method – JavaScript Design Pattern
Observer design pattern, a staple of behavioral design patterns in JavaScript, provides a means to establish a one-to-many relationship between objects. This design pattern is especially valuable for decoupling components and facilitating extensibility in software applications. By employing this pattern, you can have one object (the subject) notify multiple observers (subscribers) about changes or events without requiring them to have direct knowledge of each other. This decoupling enhances maintainability and extensibility in your software projects.
Important Topics for Observer Method in JavaScript
- Participants of Observer Pattern in JavaScript:
- Implementation of Observer Method:
- Diagram Explanation of Observer Method in JavaScript
- Publish/Subscribe Pattern:
- Differences Between Observer and Publish/Subscribe Patterns:
- Advantages of the Observer Method:
- Disadvantages of the Observer Method:
- Conclusion :
Contact Us