<C ++ implements the design mode> observer mode and observer Mode
Observer mode, also known as publish-subscribe, mvc mode, etc. in layman's terms, for example, for a stock, many people pay attention to a stock and send a person to observe the stock situation. When there is a change (observation), they will be notified to all the people who have prepared the message.
In our common mvc mode, v refers to view-view, and m Refers to model-model, which is similar to the observer mode. When the data in the model changes, the associated view is notified. in this way, the model and view are easily isolated.
The example here is about blog subscription. A blog belongs to the observed object, and a subscriber belongs to the observer. the subscriber first subscribes to (registers) the blog. Once the blog has been updated, it will traverse the registry and push the updated blog to the subscriber.
I drew a UML diagram myself. I drew it myself. A UML diagram is really helpful for writing a program. The following code is provided directly:
Observer. h:
# Ifndef OBSERVER_H # define OBSERVER_H # include <string> # include "subject. h" using namespace std; class Blog; class BlogCSDN; class Observer {public: Observer () {} virtual ~ Observer () {} virtual void Update () {}}; class ObserverBlog: public Observer {private: string m_name; // Observer name Blog * m_blog; // observed Blog, better in the form of a linked list, you can observe Multiple blogs public: ObserverBlog (string name, Blog * blog): m_name (name), m_blog (blog ){}~ ObserverBlog () {} void Update () ;}; # endif
Observer. cpp
#include "observer.h"#include<iostream>using namespace std;void ObserverBlog::Update(){string status = m_blog->GetStatus();cout << m_name << "-------" << status << endl;}
Subject. h
# Ifndef SUBJECT_H # define SUBJECT_H # include <list> # include "observer. h "using namespace std; class Observer; class Blog {private: list <Observer *> m_observers; // Observer list protected: string m_status; // status public: Blog () {} virtual ~ Blog () {} void Attach (Observer * observer); // Add the Observer void Remove (observer * Observer); // Remove the observer void Notify (); // notifies the observer of virtual void SetStatus (string s); // sets the status virtual string GetStatus (); // obtains the status}; class BlogCSDN: public Blog {private: string m_name; // The name Of The blogger is public: BlogCSDN (string name): m_name (name ){}~ BlogCSDN () {}void SetStatus (string s); string GetStatus () ;};# endif
Subject. cpp
# Include "subject. h "void Blog: Attach (Observer * observer) {m_observers.push_back (observer);} void Blog: Remove (Observer * observer) {m_observers.remove (observer);} void Blog :: notify () {list <Observer *>: iterator iter = m_observers.begin (); for (; iter! = M_observers.end (); iter ++) {(* iter)-> Update () ;}} void Blog: SetStatus (string s) {m_status = s;} string Blog:: GetStatus () {return m_status;} void BlogCSDN: SetStatus (string s) {m_status = "csdn notification:" + m_name + s;} string BlogCSDN: GetStatus () {return m_status ;}
Main. cpp
# Include "observer. h "# include" subject. h "int main () {Blog * blog = new BlogCSDN (" zy416548283 "); Observer * observer = new ObserverBlog (" tutupig ", blog ); blog-> Attach (observer); blog-> SetStatus ("publish an article in observer mode"); blog-> Publish y (); delete blog; delete observer; return 0 ;}
Compile and run:
Zy @ zyPc :~ /Code/Cplus/designPattern/observer $./a. out tutupig ------- csdn notification: zy416548283 published *** article
If you encounter cross-reference issues when writing programs by yourself (header files are referenced by each other and methods in the class are called), you can refer to the post: Click to open the link, or you can check out my questions: click Open Link
PS:
Refer to blog: Click to open the link
Reference books: <23 design patterns-C ++>, <yi design patterns>
Java Design Pattern observer pattern code
First
Public interface RandomNumberListener {// interface
Public void numberChanged (double d );
}
Second
Public class Consol implements RandomNumberListener {
@ Override
Public void numberChanged (double d ){
System. out. println (d );
}
}
Third
Public class SwingWindow
Extends JFrame
Implements RandomNumberListener {// observer
Private JLabel label = new JLabel ();
Public SwingWindow (){
This. getContentPane (). add (label );
This. setSize (300,200 );
This. setVisible (true );
}
@ Override
Public void numberChanged (double d ){
Label. setText (String. valueOf (d ));
}
}
Fourth
Public class RandomNumber {// business
Private double r;
Private List <RandomNumberListener> listeners = new ArrayList <RandomNumberListener> ();
// Add all observers
Public void addRandomNumberListener (RandomNumberListener lis ){
Listeners. add (lis );
}
Public void random (){
R = Math. random ();
// The data changes and all observers are notified.
For (RandomNumberListener lis: listeners ){
Lis. numberChanged (r );
}
}
}
Fifth
Public class Test {
Public static void main (String [] args) throws InterruptedException {
RandomNumber rn = new RandomNumber ();
SwingWindow sw = new SwingWindow ();
Consol c = new Consol ();
Rn. addRandomNumberListener (sw );
Rn. addRandomNumberListener (c );
While (true ){
Rn. random ();
Thread. sleep (new Random (). nextInt (3000) + 1000L );
}
}
}... Remaining full text>
What is the most widely used design pattern in the MVC pattern? A singleton B Observer (Observer) C Proxy (Proxy) D Bridge (Bridge)
Observer B (Observer)
==================================
Relationship between observer mode and MVC mode:
1. MVC is an architecture model. An architecture model describes the basic structure or outline of a software system. In the MVC mode, there are three roles: model, view, and controller ).
2. The observer mode can be used to implement the MVC mode. In observer mode, the topic role is the model role in MVC mode and the Controller role. The observer role is the view role in MVC mode.
Hope to help you. Pai_^