Monday, May 5, 2014

Observer Pattern

  1 #include<iostream>
  2 #include<vector>
  3 using namespace std;
  4
  5 class Notification{
  6         public:
  7                 virtual void Notify()=0;
  8 };
  9
 10 class EmailNotification: public Notification{
 11         public:
 12                 void Notify(){cout<<"Email Notification sent to.....@yahoo.com"<<endl;}
 13 };
 14
 15 class SMSNotification: public Notification{
 16         public:
 17                 void Notify(){cout<<"SMS Notification sent to.... 999999990 "<<endl;}
 18
 19 };
 20
 21 class Notifier{
 22         vector<Notification *> notifications;
 23         public:
 24         void addNotifications(Notification *notification)
 25         {
 26                 notifications.push_back(notification);
 27         }
 28         void NotifyAll()
 29         {
 30                 for(int i = 0; i < notifications.size(); i++)
 31                         notifications[i]->Notify();
 32         }
 33 };
 34
 35 int main()
 36 {
 37         cout<<"Do you want to send notifications....? Y/N:  ";
 38         Notifier *notify = new Notifier();
 39         char response;
 40         cin>> response;
 41
 42         if(response == 'Y' || response == 'y')
 43         {
 44                 EmailNotification *emailnotification = new EmailNotification();
 45                 SMSNotification *smsnotification = new SMSNotification();
 46                 notify->addNotifications(smsnotification);
 47                 notify->addNotifications(emailnotification);
 48                 notify->NotifyAll();
 49         }
 50         else
 51         {
 52                 cout<<"No Notification Sent. Bye!!"<<endl;
 53         }
 54 }

No comments:

Post a Comment