code_junkie

Which design patterns are underutilized?

Nov 11th, 2011
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <ostream>
  3. using namespace std;
  4.  
  5. // Downside: note the cyclic dependencies, typically expressed in
  6. // real life as include file dependency.
  7. struct StartMessage;
  8. struct StopMessage;
  9.  
  10. class MessageRecipient
  11. {
  12. public:
  13. // Downside: hard to add new messages
  14. virtual void handleMessage(const StartMessage& start) = 0;
  15. virtual void handleMessage(const StopMessage& stop) = 0;
  16. };
  17.  
  18. struct Message
  19. {
  20. virtual void dispatchTo(MessageRecipient& r) const = 0;
  21. };
  22.  
  23. struct StartMessage : public Message
  24. {
  25. void dispatchTo(MessageRecipient& r) const
  26. {
  27. r.handleMessage(*this);
  28. }
  29. // public member data ...
  30. };
  31.  
  32. struct StopMessage : public Message
  33. {
  34. StopMessage() {}
  35.  
  36. void dispatchTo(MessageRecipient& r) const
  37. {
  38. r.handleMessage(*this);
  39. }
  40. // public member data ...
  41. };
  42.  
  43. // Upside: easy to add new recipient
  44. class RobotArm : public MessageRecipient
  45. {
  46. public:
  47. void handleMessage(const StopMessage& stop)
  48. {
  49. cout << "Robot arm stopped" << endl;
  50. }
  51.  
  52. void handleMessage(const StartMessage& start)
  53. {
  54. cout << "Robot arm started" << endl;
  55. }
  56. };
  57.  
  58. class Conveyor : public MessageRecipient
  59. {
  60. public:
  61. void handleMessage(const StopMessage& stop)
  62. {
  63. cout << "Conveyor stopped" << endl;
  64. }
  65.  
  66. void handleMessage(const StartMessage& start)
  67. {
  68. cout << "Conveyor started" << endl;
  69. }
  70. };
  71.  
  72. void SendTo(const Message& m, MessageRecipient& r)
  73. {
  74. // magic double dispatch
  75. m.dispatchTo(r);
  76. }
  77.  
  78. int main()
  79. {
  80. Conveyor c;
  81. RobotArm r;
  82.  
  83. SendTo(StartMessage(), c);
  84. SendTo(StartMessage(), r);
  85. SendTo(StopMessage(), r);
  86. }
Add Comment
Please, Sign In to add comment