I have a observer pattern implemented and I'm using two base classes called Subject
and Observer
. - The Subject
class is an abstract class that has methods to insert the observers. And the Observer
is just an interface.
What I want is to provide a safer interface to classes that inherit to access the vector of observers and that is the way I implemented...
What would you do to make this better? Is this a bad design? Anything wrong?
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
class Observer
{
public:
virtual ~Observer() {}
virtual void notifyHuman() = 0;
virtual void notifyRobot() = 0;
};
class Subject
{
typedef std::vector<std::unique_ptr<Observer>> vector_type;
public:
virtual ~Subject() {}
void attachObserver(vector_type::value_type observer)
{
container.push_back(std::move(observer));
}
vector_type::const_iterator begin() const
{
return container.begin();
}
vector_type::const_iterator end() const
{
return container.end();
}
virtual void notifyHuman() = 0;
virtual void notifyRobot() = 0;
private:
vector_type container;
};
class FooSubject : public Subject
{
public:
FooSubject() {}
~FooSubject() {}
void notifyHuman()
{
std::for_each(begin(), end(), [] (auto & observer) {
observer->notifyHuman();
});
}
void notifyRobot()
{
std::for_each(begin(), end(), [] (auto & observer) {
observer->notifyRobot();
});
}
};
class BarObserver : public Observer
{
public:
BarObserver() {}
~BarObserver() {}
void notifyHuman()
{
std::cout << "received notification of human." << std::endl;
}
void notifyRobot()
{
std::cout << "received notification of robot." << std::endl;
}
};
int main()
{
FooSubject subject;
subject.attachObserver(std::make_unique<BarObserver>());
subject.notifyHuman();
subject.notifyRobot();
return 0;
}