use shared ptr, makr fn const

This commit is contained in:
2026-01-11 23:19:44 +00:00
parent 98e3237d37
commit 411d49bb7c
3 changed files with 21 additions and 12 deletions
@@ -1,5 +1,6 @@
#pragma once
#include <memory>
#include <unordered_map>
#include <vector>
@@ -10,14 +11,17 @@ class Subscribable {
using TSubscriber = Subscriber<TEventId, TEventInfo>;
private:
std::unordered_map<TEventId, std::vector<TSubscriber*>> subscribersMap_;
std::unordered_map<TEventId, std::vector<std::shared_ptr<TSubscriber>>>
subscribersMap_;
public:
void subscribe(const TEventId& eventId, TSubscriber* subscriber) {
void subscribe(const TEventId& eventId,
std::shared_ptr<TSubscriber> subscriber) {
subscribersMap_[eventId].push_back(subscriber);
}
void unsubscribe(const TEventId& eventId, TSubscriber* subscriber) {
void unsubscribe(const TEventId& eventId,
std::shared_ptr<TSubscriber> subscriber) {
auto entry = subscribersMap_.find(eventId);
if (entry == subscribersMap_.end()) {
return;
@@ -29,13 +33,13 @@ class Subscribable {
}
}
void notify(const TEventId& eventId, const TEventInfo& eventInfo) {
void notify(const TEventId& eventId, const TEventInfo& eventInfo) const {
auto entry = subscribersMap_.find(eventId);
if (entry == subscribersMap_.end()) {
return;
}
for (TSubscriber* subscriber : entry->second) {
for (auto& subscriber : entry->second) {
subscriber->onNotification(eventId, eventInfo);
}
}
@@ -2,6 +2,9 @@
void InventoryManager::setInventory(const ProductId& productId,
ProductCount quantity) {
ProductCount oldQuantity = inventory_[productId];
inventory_[productId] = quantity;
this->notify(productId, quantity);
if (oldQuantity != quantity) {
this->notify(productId, quantity);
}
}
+8 -6
View File
@@ -1,16 +1,18 @@
#include <memory>
#include "app/inventory_manager.hpp"
#include "app/services.hpp"
int main() {
InventoryManager inventoryManager;
SmsService smsService;
EmailService emailService;
LogService logService;
auto smsService = std::make_shared<SmsService>();
auto emailService = std::make_shared<EmailService>();
auto logService = std::make_shared<LogService>();
inventoryManager.subscribe("ProductA", &smsService);
inventoryManager.subscribe("ProductB", &emailService);
inventoryManager.subscribe("ProductA", &logService);
inventoryManager.subscribe("ProductA", smsService);
inventoryManager.subscribe("ProductB", emailService);
inventoryManager.subscribe("ProductA", logService);
inventoryManager.setInventory("ProductA", 100);
inventoryManager.setInventory("ProductB", 200);