×

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is useful in cases where you want to maintain consistency between related objects without making the objects tightly coupled.

Example

Here is an example of the Observer design pattern in C++:

#include <iostream>
#include <vector>
// Forward declaration of the Subject class
class Subject;
// The Observer class has a virtual update function that can be
// overridden by derived classes. It also has a constructor that
// takes a Subject as an argument and registers itself as an observer
// of that subject.
class Observer {
 public:
Observer(Subject* subject) {
    subject_ = subject;
    subject_->Attach(this);
  }
  virtual ~Observer() {}
  virtual void Update() = 0;
 private:
  Subject* subject_;
};
// The Subject class has a vector of observers and functions to add
// or remove observers from the vector. It also has a virtual function
// called Notify that can be overridden by derived classes.
class Subject {
 public:
Subject() {}
  virtual ~Subject() {}
  void Attach(Observer* observer) {
    observers_.push_back(observer);}
  void Detach(Observer* observer) {
    for (size_ti = 0; i<observers_.size(); ++i) {
      if (observers_[i] == observer) {
observers_.erase(observers_.begin() + i);
break;}   } }
  virtual void Notify() {
    for (auto observer : observers_) {
      observer->Update();} }
 private:
std::vector<Observer*> observers_;};
// A concrete subject class that stores a single integer value.
// It has a function called SetValue that updates the value and
// notifies observers when the value changes.
class IntSubject : public Subject {
 public:
IntSubject() : value_(0) {}
  int GetValue() const { return value_; }
  void SetValue(int value) {
    if (value_ != value) {
      value_ = value;
Notify();}}
private:
  int value_;  };
// A concrete observer class that displays the value of an IntSubject
class IntObserver : public Observer {
public:
IntObserver(IntSubject* subject) : Observer(subject) {}
  void Update() override {
std::cout<< "IntObserver: Subject value is now "
<<static_cast<IntSubject*>(subject_)->GetValue() << std::endl;
};
  }
int main() {
IntSubject subject;
IntObserver observer1(&subject);
IntObserver observer2(&subject);
subject.SetValue(5);
subject.SetValue(10);
subject.SetValue(10);  // No update should be triggered
  return 0;
}

This example defines a Subject class with functions to attach and detach observers and a virtual Notify function that derived classes can override.

When to Use Observer Design?

It would be best if you used the Observer design pattern in C++ to establish a one-to-many relationship between objects, such that when one object (the subject) changes state, all the dependent objects (the observers) are notified and updated automatically.

This pattern is useful in cases where you want to maintain consistency between related objects without making the objects tightly coupled. For example, consider a graphical user interface (GUI) where multiple widgets (observers) display the same data and need to be updated whenever the data changes. Using the Observer pattern, you can design the widgets and the data as separate classes and have the widgets register themselves as observers of the data. When the data changes, it can notify all its registered observers, then update its display.

Another example where the Observer pattern can be useful is in a stock ticker application, where multiple clients (observers) are interested in receiving updates on the latest stock prices. The stock ticker (the subject) can notify all the registered clients (the observers) whenever the prices change.

In general, you should use the Observer pattern when:

  • There is a one-to-many relationship between objects, such that when one objects changes state, all its dependents are notified and updated automatically.
  • You want to abstract the details of the objects that depend on the subject from the subject itself.
  • You want to change the dependencies between objects at runtime.You want to minimize the coupling between objects, such that the subject and its dependents are loosely coupled.

Advantages of Observer Design Pattern

The Observer design pattern has several advantages:

  • It decouples the subject from its observers, which makes it easier to change the subject and the observers independently.
  • It allows a subject to notifying its observers generically without the subject knowing the specifics of the observers.
  • It allows a subject to have any number of observers, which can be added or removed at runtime.
  • It allows observers to be notified of a subject's state changes as soon as they occur, rather than polling the subject for updates.
  • It allows observers to be added or removed from a subject dynamically, at runtime, without modifying the subject's code.

Related Topics

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.