Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Observer pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===C++=== This is a C++11 implementation. <syntaxhighlight lang="c++"> #include <functional> #include <iostream> #include <list> class Subject; //Forward declaration for usage in Observer class Observer { public: explicit Observer(Subject& subj); virtual ~Observer(); Observer(const Observer&) = delete; // rule of three Observer& operator=(const Observer&) = delete; virtual void update( Subject& s) const = 0; private: // Reference to a Subject object to detach in the destructor Subject& subject; }; // Subject is the base class for event generation class Subject { public: using RefObserver = std::reference_wrapper<const Observer>; // Notify all the attached observers void notify() { for (const auto& x: observers) { x.get().update(*this); } } // Add an observer void attach(const Observer& observer) { observers.push_front(observer); } // Remove an observer void detach(Observer& observer) { observers.remove_if( [&observer ](const RefObserver& obj) { return &obj.get()==&observer; }); } private: std::list<RefObserver> observers; }; Observer::Observer(Subject& subj) : subject(subj) { subject.attach(*this); } Observer::~Observer() { subject.detach(*this); } // Example of usage class ConcreteObserver: public Observer { public: ConcreteObserver(Subject& subj) : Observer(subj) {} // Get notification void update(Subject&) const override { std::cout << "Got a notification" << std::endl; } }; int main() { Subject cs; ConcreteObserver co1(cs); ConcreteObserver co2(cs); cs.notify(); } </syntaxhighlight> The program output is like <syntaxhighlight lang="c++"> Got a notification Got a notification </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)