Observer mode of design mode (C++)

Author: Zhai Tianbao Steven
Copyright statement: The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source

1. What is the observer pattern?

       The observer pattern is a behavioral software design pattern that defines a one-to-many dependency relationship between objects. When the state of the observed object changes, all observers make corresponding changes. Signals and slots in Qt are a typical observer pattern.

       Advantages of the observer pattern:

  1. Both sides of the coupling rely on the abstraction and don't need to know the concrete.
  2. Provides a stable information update delivery mechanism.
  3. Good scalability.

      Disadvantages of observer pattern:

  1. When there are too many observers, it may take a long time to notify the observers one by one.
  2. If a certain observer freezes, it may affect the entire process. Generally, an asynchronous mechanism is used to solve the problem, but at the same time, attention should be paid to program security.

2. Observer mode

2.1 Structure diagram

       The client is the Main function. When the observed object changes, all observers respond.

2.2 Code example

       Scene description: The car at the intersection is waiting for the traffic light to change.

//Observer.h
/****************************************************/
#pragma once
#include <iostream>
#include <unordered_map>
#include <vector>
#include <list>
#include <string>

using namespace std;

// 抽象观察者
class Observer 
{
public:
	// 构造函数
	Observer(int num):m_number(num){}

	// 更新
    virtual void update(bool flag) = 0;

protected:
	int m_number;
};

// 抽象主题-被观察者
class Subject 
{
public:
	// 连接
    virtual void attach(Observer* observer) = 0;

	// 断连
    virtual void detach(Observer* observer) = 0;

	// 通知
    virtual void notify(bool flag) = 0;

protected:
	vector<Observer*> observers;
};

// 具体主题-红绿灯
class TrafficLight : public Subject
{
public:
	// 连接
	virtual void attach(Observer* observer) {
        observers.push_back(observer);
    }

	// 断连
	virtual void detach(Observer* observer) {
		for (auto iter = observers.begin(); iter != observers.end();){
			if (*iter == observer){
				iter = observers.erase(iter);
			}
			else{
				iter++;
			}
		}
    }

	// 通知
	virtual void notify(bool flag) {
		if (flag) {
			cout << "绿灯通行。" << endl;
			for (auto observer : observers) {
				observer->update(flag);
			}
		}
		else {
			cout << "红灯停止。" << endl;
			for (auto observer : observers) {
				observer->update(flag);
			}
		}
    }

};

// 具体观察者-汽车
class Car : public Observer 
{
public:
	// 构造函数
	Car(int num) :Observer(num) {}

	// 更新
	virtual void update(bool flag) {
		if (flag) {
			cout << m_number << "号汽车:发动。" << endl;
		}
		else {
			cout << m_number << "号汽车:停止。" << endl;
		}
    }
};
//main.cpp
/****************************************************/
#include <iostream>
#include <string>
#include "Observer.h"

using namespace std;

int main() 
{
	// 创建主题对象
	Subject *subject = new TrafficLight();

	// 创建观察者对象
	Observer *observer1 = new Car(1);
	Observer *observer2 = new Car(2);
	Observer *observer3 = new Car(3);
	Observer *observer4 = new Car(4);

	// 连接观察者
	subject->attach(observer1);
	subject->attach(observer2);
	subject->attach(observer3);
	subject->attach(observer4);

	// 绿灯行
	subject->notify(true);

	// 3号车通过,不需要再观察
	subject->detach(observer3);
	cout << "3号车已通过。" << endl;

	// 红灯停
	subject->notify(false);

	// 删除
	delete subject;
	delete observer1;
	delete observer2;
	delete observer3;
	delete observer4;
	subject = nullptr;
	observer1 = nullptr;
	observer2 = nullptr;
	observer3 = nullptr;
	observer4 = nullptr;

	return 0;
}

       The program results are as follows.

       When the traffic light is not green, there are 4 cars waiting. After the green light passes, only car No. 3 passes. At this time, car No. 3 no longer needs to observe the current status of the traffic light and unbind it; then the red light is on, and the other 3 cars Continue to stop and wait.

3. Summary

       I try my best to express my understanding of the Observer pattern with more popular words and intuitive code routines. There may be some things that are not thoughtful. If you have different opinions, welcome to communicate in the comment area! I hope my example will help you understand the Observer pattern better.

       If the article helps you, you can give me a like to let me know, I will be very happy ~ come on!

Guess you like

Origin blog.csdn.net/zhaitianbao/article/details/130132800