Adapter.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <stdio.h>
  2. /*
  3. * C++ Design Patterns: ADAPTER
  4. * http://www.plantuml.com/plantuml/uml/XP9DRi8m48NtFiL8NG2gGaIMA8g0jhkggYXxD76cgYl7Zkm94lsvIxUSWulL3I652BMpchpvdbzipSmpEgvBBU81p6_dZwkx9GnY4KeP9lUCac1UO1LwU1SGwWfiHGvPMJCSYKyXf4RluKOhCjmorr3OjMoKzMNQ6kc8wVpegAyFbMdJQJBw5qb6RVYboEwSuozsmaAzeNDqWKtwR7B6YXTL451PyHPAAdDoNeZZZTAeVP9VvIEAkj1pjNSdqVk6AEkCVymI8Onb0lJmC14GAispL5fjtTJPBUg5hYbhVMdS3B8qphCZkzfMDFqHu8bTBRbsg9lPShz3hJn1RGYaDHjoNbaJsh92Lhacm0r9Q61D7f2P38UcgE6m1sEunnDhGnO1wDRC0ta6TqZQxmZsNw07odX68nNogSdchyH-BCWKO2oJc8MkBlKt
  5. *
  6. */
  7. #include <iostream>
  8. #include <string>
  9. #include <functional>
  10. /* Legacy code -------------------------------------------------------------- */
  11. struct Adapter {
  12. Adapter() { std::cout << "Constructor Adapter" << std::endl;}
  13. virtual void operation() = 0;
  14. };
  15. struct Adaptee1 : Adapter {
  16. void Adaptee1Bizarre() { std::cout << "perform Adaptee1Bizarre" << std::endl;}
  17. void operation() { Adaptee1Bizarre(); }
  18. };
  19. //exported interface to the client
  20. class Client {
  21. public:
  22. void do_client_operation(Adapter &do_client){
  23. std::cout << "do_client operation()" << std::endl;
  24. do_client.operation(); // Interface from Adapter
  25. };
  26. };
  27. // Evolution with ConcreteAdapter & Adaptee2
  28. struct Adaptee2 { // Introduced later on - don't call Adapter Constructor
  29. void Adaptee2Bizarre() { std::cout << "perform Adaptee2Bizarre" << std::endl; }
  30. //void operation() { Adaptee2Bizarre(); }
  31. };
  32. struct ConcreteAdapter : Adapter { // Expanding Adapter with lambda function
  33. std::function<void()> m_request;
  34. //lambda function, copy cm in m_request and call specific adaptee operation
  35. ConcreteAdapter(Adaptee1* cm1) { m_request = [cm1] ( ) { std::cout << "lambda cm1" << std::endl; cm1->Adaptee1Bizarre(); }; }
  36. ConcreteAdapter(Adaptee2* cm2) { m_request = [cm2] ( ) { std::cout << "lambda cm2" << std::endl; cm2->Adaptee2Bizarre(); }; }
  37. void operation() { m_request(); }
  38. };
  39. int main() {
  40. Client client;
  41. std::cout << "new Adaptee1" << std::endl;
  42. ConcreteAdapter adp1(new Adaptee1());
  43. client.do_client_operation(adp1);
  44. std::cout << "new Adaptee2" << std::endl;
  45. ConcreteAdapter adp2(new Adaptee2());
  46. client.do_client_operation(adp2);
  47. }