Advertisement
Guest User

Untitled

a guest
Jul 26th, 2015
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. class ObserverInterface
  7. {
  8. public:
  9. virtual void update(std::string message) = 0;
  10. };
  11.  
  12. class concreteObserver : ObserverInterface
  13. {
  14. std::string name;
  15. std::string message;
  16. public:
  17. concreteObserver(std::string name)
  18. :name(name)
  19. {}
  20. void update(std::string message)
  21. {
  22. this->message = message;
  23.  
  24. std::cout << "Dear " << name << ", " << message << " from eBay" << std::endl;
  25. }
  26. };
  27.  
  28. class SubjectInterface
  29. {
  30. public:
  31. void subscribe(concreteObserver *subscriber)
  32. {
  33. subscribers.push_back(subscriber);
  34. }
  35. void unsubscribe(concreteObserver *subscriber)
  36. {
  37. subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), subscriber), subscribers.end());
  38. }
  39. void notify(std::string message)
  40. {
  41. std::vector<concreteObserver*>::const_iterator itr = subscribers.begin();
  42. while (itr != subscribers.end())
  43. {
  44. (*itr)->update(message);
  45. ++itr;
  46. }
  47. }
  48. private:
  49. std::vector<concreteObserver*> subscribers;
  50. };
  51.  
  52. class concreteSubject : public SubjectInterface
  53. {
  54. public:
  55. void newMessage(std::string msg)
  56. {
  57. notify(msg);
  58. }
  59. };
  60.  
  61. int main(int argc, char* argv[])
  62. {
  63. // EBAY
  64. concreteSubject ebay;
  65.  
  66. // USERS
  67. concreteObserver user1("Steven");
  68. concreteObserver user2("John");
  69.  
  70. // SUBSCRIBERS TO EBAY
  71. ebay.subscribe(&user1);
  72. ebay.subscribe(&user2);
  73.  
  74. // EBAY SENDS NEW PROMOTIONS TO SUBSCRIBERS
  75. ebay.newMessage("enjoy free weekend listings");
  76.  
  77. // UNSUBSCRIBE FROM EBAY
  78. ebay.unsubscribe(&user2);
  79.  
  80. // EBAY SENDS NEW PROMOTION TO SUBSCRIBERS
  81. ebay.newMessage("free listings extended until 1st August");
  82.  
  83. std::cout << std::endl << std::endl;
  84. system("pause");
  85. return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement