Design Pattern-Observer mode (C + +)

Source: Internet
Author: User
Tags abstract

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.