Evgenii Legotckoi
Sept. 18, 2018, 3:44 p.m.

Example - "Builder" design pattern in C++

Content

Discussion. The forte of Builder is constructing a complex object step by step. An abstract base class declares the standard construction process, and concrete derived classes define the appropriate implementation for each step of the process. In this example, "distributed work packages" have been abstracted to be persistent and platform independent.

This means that the platform-specific mechanism for implementing files, queues, and concurrency pathways is defined in each platform's concrete derived class. A single "reader" object (i.e. parser) retrieves the archived specification for a DistrWorkPackage and proceeds to delegate each build step to the builder object that was registered by the client. Upon completion, the client retrieves the end result from the builder.


  1. #include <iostream.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. enum PersistenceType
  6. {
  7. File, Queue, Pathway
  8. };
  9.  
  10. struct PersistenceAttribute
  11. {
  12. PersistenceType type;
  13. char value[30];
  14. };
  15.  
  16. class DistrWorkPackage
  17. {
  18. public:
  19. DistrWorkPackage(char *type)
  20. {
  21. sprintf(_desc, "Distributed Work Package for: %s", type);
  22. }
  23. void setFile(char *f, char *v)
  24. {
  25. sprintf(_temp, "\n File(%s): %s", f, v);
  26. strcat(_desc, _temp);
  27. }
  28. void setQueue(char *q, char *v)
  29. {
  30. sprintf(_temp, "\n Queue(%s): %s", q, v);
  31. strcat(_desc, _temp);
  32. }
  33. void setPathway(char *p, char *v)
  34. {
  35. sprintf(_temp, "\n Pathway(%s): %s", p, v);
  36. strcat(_desc, _temp);
  37. }
  38. const char *getState()
  39. {
  40. return _desc;
  41. }
  42. private:
  43. char _desc[200], _temp[80];
  44. };
  45.  
  46. class Builder
  47. {
  48. public:
  49. virtual void configureFile(char*) = 0;
  50. virtual void configureQueue(char*) = 0;
  51. virtual void configurePathway(char*) = 0;
  52. DistrWorkPackage *getResult()
  53. {
  54. return _result;
  55. }
  56. protected:
  57. DistrWorkPackage *_result;
  58. };
  59.  
  60. class UnixBuilder: public Builder
  61. {
  62. public:
  63. UnixBuilder()
  64. {
  65. _result = new DistrWorkPackage("Unix");
  66. }
  67. void configureFile(char *name)
  68. {
  69. _result->setFile("flatFile", name);
  70. }
  71. void configureQueue(char *queue)
  72. {
  73. _result->setQueue("FIFO", queue);
  74. }
  75. void configurePathway(char *type)
  76. {
  77. _result->setPathway("thread", type);
  78. }
  79. };
  80.  
  81. class VmsBuilder: public Builder
  82. {
  83. public:
  84. VmsBuilder()
  85. {
  86. _result = new DistrWorkPackage("Vms");
  87. }
  88. void configureFile(char *name)
  89. {
  90. _result->setFile("ISAM", name);
  91. }
  92. void configureQueue(char *queue)
  93. {
  94. _result->setQueue("priority", queue);
  95. }
  96. void configurePathway(char *type)
  97. {
  98. _result->setPathway("LWP", type);
  99. }
  100. };
  101.  
  102. class Reader
  103. {
  104. public:
  105. void setBuilder(Builder *b)
  106. {
  107. _builder = b;
  108. }
  109. void construct(PersistenceAttribute[], int);
  110. private:
  111. Builder *_builder;
  112. };
  113.  
  114. void Reader::construct(PersistenceAttribute list[], int num)
  115. {
  116. for (int i = 0; i < num; i++)
  117. if (list[i].type == File)
  118. _builder->configureFile(list[i].value);
  119. else if (list[i].type == Queue)
  120. _builder->configureQueue(list[i].value);
  121. else if (list[i].type == Pathway)
  122. _builder->configurePathway(list[i].value);
  123. }
  124.  
  125. const int NUM_ENTRIES = 6;
  126. PersistenceAttribute input[NUM_ENTRIES] =
  127. {
  128. {
  129. File, "state.dat"
  130. }
  131. ,
  132. {
  133. File, "config.sys"
  134. }
  135. ,
  136. {
  137. Queue, "compute"
  138. }
  139. ,
  140. {
  141. Queue, "log"
  142. }
  143. ,
  144. {
  145. Pathway, "authentication"
  146. }
  147. ,
  148. {
  149. Pathway, "error processing"
  150. }
  151. };
  152.  
  153. int main()
  154. {
  155. UnixBuilder unixBuilder;
  156. VmsBuilder vmsBuilder;
  157. Reader reader;
  158.  
  159. reader.setBuilder(&unixBuilder);
  160. reader.construct(input, NUM_ENTRIES);
  161. cout << unixBuilder.getResult()->getState() << endl;
  162.  
  163. reader.setBuilder(&vmsBuilder);
  164. reader.construct(input, NUM_ENTRIES);
  165. cout << vmsBuilder.getResult()->getState() << endl;
  166. }

Output

  1. Distributed Work Package for: Unix
  2. File(flatFile): state.dat
  3. File(flatFile): config.sys
  4. Queue(FIFO): compute
  5. Queue(FIFO): log
  6. Pathway(thread): authentication
  7. Pathway(thread): error processing
  8. Distributed Work Package for: Vms
  9. File(ISAM): state.dat
  10. File(ISAM): config.sys
  11. Queue(priority): compute
  12. Queue(priority): log
  13. Pathway(LWP): authentication
  14. Pathway(LWP): error processing

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html