Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is a reference implementation (from <a href="https://en.wikipedia.org/w/index.php?title=Observer_pattern&amp;oldid=342672104" rel="nofollow noreferrer">Wikipedia</a>).</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;map&gt; #include &lt;boost/foreach.hpp&gt; class SupervisedString; class IObserver{ public: virtual void handleEvent(const SupervisedString&amp;) = 0; }; class SupervisedString{ // Observable class std::string _str; std::map&lt;IObserver* const, IObserver* const&gt; _observers; typedef std::map&lt;IObserver* const, IObserver* const&gt;::value_type item; void _Notify(){ BOOST_FOREACH(item iter, _observers){ iter.second-&gt;handleEvent(*this); } } public: void add(IObserver&amp; ref){ _observers.insert(item(&amp;ref, &amp;ref)); } void remove(IObserver&amp; ref){ _observers.erase(&amp;ref); } const std::string&amp; get() const{ return _str; } void reset(std::string str){ _str = str; _Notify(); } }; class Reflector: public IObserver{ // Prints the observed string into std::cout public: virtual void handleEvent(const SupervisedString&amp; ref){ std::cout&lt;&lt;ref.get()&lt;&lt;std::endl; } }; class Counter: public IObserver{ // Prints the length of observed string into std::cout virtual void handleEvent(const SupervisedString&amp; ref){ std::cout&lt;&lt;"length = "&lt;&lt;ref.get().length()&lt;&lt;std::endl; } }; int main(){ SupervisedString str; Reflector refl; Counter cnt; str.add(refl); str.reset("Hello, World!"); std::cout&lt;&lt;std::endl; str.remove(refl); str.add (cnt); str.reset("World, Hello!"); std::cout&lt;&lt;std::endl; return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload