Author: Liu Miangang e-mail:liumgj@163.com
Observer mode is one of the most widely used design patterns, has been implemented in C #, the following is the implementation of C + +, in C + + implementation, C + + has no interface concept, but you can use the abstract class class instead of Java or C # interface, in C + + abstract class from the derived class in the function (method), must be defined as pure virtual functions, so that they can be accessed by pointers to base classes in later use, and there is a feature in the object-oriented language that polymorphism can only access parts of both.
#include
#include
#include
using namespace Std;
Class Observer;
Class Subject
{
Public
virtual void Attach (Observer *o) = 0;
virtual void change () = 0;
virtual void Setweather (string str) = 0;
Virtual String getWeather () = 0;
};
Class Observer
{
Public
Virtual String getName () = 0;
virtual void update (Subject *s) = 0;
};
Class Earth:public Subject
{
Private
String weather;
List
*l;
Public
Earth ()
{
L = new List
();
}
void Attach (Observer *o)
{
This->l->push_back (o);
};
void Change ()
{
for (list
:: Iterator It=l->begin (); It!=l->end (); ++it)
{
(*it)->update (this);
}
};
void Setweather (String str)
{
this->weather=str;
Change ();
};
String GetWeather ()
{
Return this->weather;
};
};
Class Satellite:public Observer
{
Private
String name;
Public
Satellite (String str)
{
NAME=STR;
}
String GetName ()
{
return name;
};
void Update (Subject *s)
{
Cout〈〈this->getname () + "" +s->getweather () <
};
};
int main ()
{
Earth E;
Satellite *S1 = new Satellite ("the number One");
Satellite *S2 = new Satellite ("cloud second");
Satellite *S3 = new Satellite ("cloud Third");
Satellite *S4 = new Satellite ("cloud Fourth");
E.attach (S1);
E.attach (S2);
E.attach (S3);
E.attach (S4);
E.setweather ("fine");
return 0;
}