├── .gitignore
├── LICENSE
├── README.md
├── behavioral
├── chain_of_responsibility
│ ├── README.md
│ └── main.go
├── command
│ ├── README.md
│ └── main.go
├── interpreter
│ ├── README.md
│ └── main.go
├── iterator
│ ├── README.md
│ └── main.go
├── mediator
│ ├── README.md
│ └── main.go
├── memento
│ ├── README.md
│ └── main.go
├── observer
│ ├── README.md
│ └── main.go
├── state
│ ├── README.md
│ └── main.go
├── strategy
│ ├── README.md
│ └── main.go
├── template
│ ├── README.md
│ └── main.go
└── visitor
│ ├── README.md
│ └── main.go
├── creational
├── abstract_factory
│ ├── README.md
│ └── main.go
├── builder
│ ├── README.md
│ └── main.go
├── factory
│ ├── README.md
│ ├── log.txt
│ └── main.go
├── prototype
│ ├── README.md
│ └── main.go
└── singleton
│ ├── README.md
│ └── main.go
├── go.mod
├── go.sum
├── other
├── data_access_object
│ ├── README.md
│ └── main.go
├── dependency_injection
│ ├── README.md
│ ├── article.txt
│ └── main.go
├── repository
│ ├── README.md
│ └── main.go
└── service_locator
│ ├── README.md
│ └── main.go
└── structural
├── adapter
├── README.md
└── main.go
├── bridge
├── README.md
└── main.go
├── composite
├── README.md
└── main.go
├── decorator
├── README.md
└── main.go
├── facade
├── README.md
└── main.go
├── flyweight
├── README.md
└── main.go
└── proxy
├── README.md
└── main.go
/.gitignore:
--------------------------------------------------------------------------------
1 | # If you prefer the allow list template instead of the deny list, see community template:
2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
3 | #
4 | # Binaries for programs and plugins
5 | *.exe
6 | *.exe~
7 | *.dll
8 | *.so
9 | *.dylib
10 |
11 | # Test binary, built with `go test -c`
12 | *.test
13 |
14 | # Output of the go coverage tool, specifically when used with LiteIDE
15 | *.out
16 |
17 | # Dependency directories (remove the comment below to include it)
18 | # vendor/
19 |
20 | # Go workspace file
21 | go.work
22 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # design-patterns-in-go
2 |
3 | A list of design patterns implemented in Go with REAL WORLD examples!
4 |
5 | ## "Gang of Four" patterns
6 |
7 | ### Creational Patterns
8 |
9 | - **Singleton**: Ensures a class only has one instance and provides a global point of access to it.
10 | - **Factory**: Provides an interface for creating objects in a super class, but allows subclasses to alter the type of objects that will be created.
11 | - **Abstract Factory**: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
12 | - **Builder**: Separates the construction of a complex object from its representation so that the same construction process can create different representations.
13 | - **Prototype**: Specifies the kind of objects to create using a prototypical instance and create new objects by copying this prototype.
14 |
15 | ### Structural Patterns
16 |
17 | - **Adapter**: Converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
18 | - **Decorator**: Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
19 | - **Facade**: Provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
20 | - **Composite**: Composes objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
21 | - **Proxy**: Provides a surrogate or placeholder for another object to control access to it.
22 | - **Bridge**: Decouples an abstraction from its implementation so that the two can vary independently.
23 | - **Flyweight**: Uses sharing to support large numbers of fine-grained objects efficiently.
24 |
25 | ### Behavioral Patterns
26 |
27 | - **Observer**: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
28 | - **Command**: Encapsulates a request as an object, thereby letting you parameterize clients with queues, requests, and operations.
29 | - **Strategy**: Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
30 | - **State**: Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
31 | - **Template**: Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
32 | - **Iterator**: Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
33 | - **Mediator**: Defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
34 | - **Memento**: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
35 | - **Chain of Responsability**: Used to achieve loose coupling in software design where a request from the client is passed to a chain of objects to process them.
36 | - **Interpreter**: Defines a grammatical representation for a language and provides an interpreter to deal with this grammar.
37 | - **Visitor**: Used when we have to perform an operation on a group of similar kind of Objects.
38 |
39 | ## Other Patterns
40 |
41 | - **Active Record Pattern**: Found in many modern ORM (Object Relational Mapping) libraries, the Active Record pattern ties database access directly to an object, where the object mirrors the database table. Each instance of the object corresponds to a row in the table.
42 | - **Repository Pattern**: Acts as a kind of in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction.
43 | - **Data Access Object (DAO) Pattern**: Provides an abstract interface to a database or a persistent storage mechanism.
44 | - **Dependency Injection (DI) Pattern**: A way to achieve Inversion of Control (IoC) in a system by breaking dependencies between higher-level and lower-level software layers.
45 | - **Model-View-ViewModel (MVVM) Pattern**: Primarily used for designing the user interface. It divides an application into three interconnected components: Model (represents the data), View (represents the UI), and ViewModel (acts as a bridge that handles the data presentation in the View).
46 | - **CQRS (Command Query Responsibility Segregation)**: A pattern where you separate the command (write) operations from the query (read) operations, ensuring that a method is either a command that performs an action or a query that returns data, but not both.
47 | - **Event Sourcing**: Capturing all changes to an application state as a sequence of events, allowing for replaying these events to restore the application's state.
48 | - **Flux/Redux Pattern**: Used mainly in frontend frameworks like React. It involves a unidirectional data flow where the view sends actions to a central dispatcher, which updates the store, and the changed state then reflects in the view.
49 | - **Saga Pattern**: A mechanism to manage long-running, complex processes or workflows. Sagas manage failures, maintain consistency, and coordinate activities.
50 | - **Service Locator Pattern**: Provides a centralized point from which objects can retrieve services (like dependency injection but involves the client requesting its dependencies).
51 | - **Null Object Pattern**: A design pattern that uses polymorphism to represent the absence of an object by providing an alternative that offers default do-nothing behavior.
52 | - **Value Object Pattern**: Small objects that represent a descriptive aspect of the domain with no conceptual identity. They are immutable, meaning that they cannot be altered once they are created.
53 | - **Thread Pool Pattern**: Allows a limited set of threads to be reused for executing multiple tasks.
54 |
--------------------------------------------------------------------------------
/behavioral/chain_of_responsibility/README.md:
--------------------------------------------------------------------------------
1 | # Chain of Responsibility
2 |
3 | The Chain of Responsibility design pattern is a behavioral pattern that allows you to pass a request along a chain of handlers. Each handler decides either to process the request or to pass it along the chain. This pattern allows you to decouple the sender and receiver components, making the code more modular and easier to maintain.
4 |
5 | In the Chain of Responsibility pattern, usually, each handler has a reference to the next handler in the chain. A handler decides whether it can handle the request; if it can, it does so, otherwise, it delegates the request to the next handler in the chain.
6 |
7 | ### Participants in the Chain of Responsibility Pattern
8 |
9 | - **Handler**: The interface that declares the method for handling requests.
10 | - **ConcreteHandler**: The class that implements the Handler interface and performs the actual work, or delegates the work to the next handler in the chain.
11 | - **Client**: The class that initiates the request to a handler on the chain.
12 |
13 | ## Example
14 |
15 | Let's consider a simple example where we have different levels of logging: `Info`, `Warning`, and `Error`. Each logging level is handled by a different logger. However, if one logger can't handle a particular log level, it passes the request to the next logger in the chain.
16 |
17 | Here is how you can implement this in Go:
18 |
19 | ```go
20 | // Log levels
21 | const (
22 | Info = iota
23 | Warning
24 | Error
25 | )
26 |
27 | // Handler interface
28 | type Logger interface {
29 | SetNext(Logger)
30 | LogMessage(int, string)
31 | }
32 |
33 | // ConcreteHandler
34 | type ConsoleLogger struct {
35 | level int
36 | next Logger
37 | }
38 |
39 | func (c *ConsoleLogger) SetNext(next Logger) {
40 | c.next = next
41 | }
42 |
43 | func (c *ConsoleLogger) LogMessage(level int, message string) {
44 | if c.level <= level {
45 | fmt.Printf("Writing to console: %s\n", message)
46 | }
47 | if c.next != nil {
48 | c.next.LogMessage(level, message)
49 | }
50 | }
51 |
52 | // Another ConcreteHandler
53 | type ErrorLogger struct {
54 | level int
55 | next Logger
56 | }
57 |
58 | func (e *ErrorLogger) SetNext(next Logger) {
59 | e.next = next
60 | }
61 |
62 | func (e *ErrorLogger) LogMessage(level int, message string) {
63 | if e.level <= level {
64 | fmt.Printf("Writing to error log: %s\n", message)
65 | }
66 | if e.next != nil {
67 | e.next.LogMessage(level, message)
68 | }
69 | }
70 |
71 | func main() {
72 | // Setting up the chain
73 | consoleLogger := &ConsoleLogger{level: Info}
74 | errorLogger := &ErrorLogger{level: Error}
75 |
76 | consoleLogger.SetNext(errorLogger)
77 |
78 | // Making requests
79 | consoleLogger.LogMessage(Info, "This is an informational message.")
80 | consoleLogger.LogMessage(Error, "This is an error message.")
81 | }
82 | ```
83 |
84 | In this example:
85 |
86 | - `Logger` is the `Handler` interface that defines the method for logging messages.
87 | - `ConsoleLogger` and `ErrorLogger` are `ConcreteHandlers`. Each decides whether it can handle the given logging level or pass it to the next handler in the chain.
88 | - The `main()` function acts as the `Client` that initiates the requests.
89 |
90 | Run the code, and you'll see that depending on the log level, the appropriate logger(s) handle the message.
91 |
92 | With the Chain of Responsibility pattern, you can easily add more loggers in the chain without modifying the existing code, thus following the Open/Closed Principle.
93 |
--------------------------------------------------------------------------------
/behavioral/chain_of_responsibility/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Log levels
6 | const (
7 | Info = iota
8 | Warning
9 | Error
10 | )
11 |
12 | // Handler interface
13 | type Logger interface {
14 | SetNext(Logger)
15 | LogMessage(int, string)
16 | }
17 |
18 | // ConcreteHandler
19 | type ConsoleLogger struct {
20 | level int
21 | next Logger
22 | }
23 |
24 | func (c *ConsoleLogger) SetNext(next Logger) {
25 | c.next = next
26 | }
27 |
28 | func (c *ConsoleLogger) LogMessage(level int, message string) {
29 | if c.level <= level {
30 | fmt.Printf("Writing to console: %s\n", message)
31 | }
32 | if c.next != nil {
33 | c.next.LogMessage(level, message)
34 | }
35 | }
36 |
37 | // Another ConcreteHandler
38 | type ErrorLogger struct {
39 | level int
40 | next Logger
41 | }
42 |
43 | func (e *ErrorLogger) SetNext(next Logger) {
44 | e.next = next
45 | }
46 |
47 | func (e *ErrorLogger) LogMessage(level int, message string) {
48 | if e.level <= level {
49 | fmt.Printf("Writing to error log: %s\n", message)
50 | }
51 | if e.next != nil {
52 | e.next.LogMessage(level, message)
53 | }
54 | }
55 |
56 | func main() {
57 | // Setting up the chain
58 | consoleLogger := &ConsoleLogger{level: Info}
59 | errorLogger := &ErrorLogger{level: Error}
60 |
61 | consoleLogger.SetNext(errorLogger)
62 |
63 | // Making requests
64 | consoleLogger.LogMessage(Info, "This is an informational message.")
65 | consoleLogger.LogMessage(Error, "This is an error message.")
66 | }
67 |
--------------------------------------------------------------------------------
/behavioral/command/README.md:
--------------------------------------------------------------------------------
1 | # Command
2 |
3 | The command design pattern is a behavioral design pattern used to encapsulate a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations. It also allows for the decoupling of the sender and receiver objects. The Command Pattern consists of the following main components:
4 |
5 | - Command: This defines an interface for executing an operation.
6 | - ConcreteCommand: This is a subclass of Command and implements the execute method by invoking the corresponding operation on the receiver object.
7 | - Client: The Client creates a ConcreteCommand object and sets its receiver.
8 | - Invoker: It asks the command to carry out the request.
9 | - Receiver: It knows how to perform the operation to satisfy a request.
10 |
11 | The command pattern can be particularly useful when you need to allow for undo functionality, queuing of commands, task scheduling or logging of command operations. It also provides greater flexibility in terms of organizing code and adding new commands without modifying existing code.
12 |
13 | ## Example
14 |
15 | Here's a practical example that could be part of a text editor, where we implement a simple undo functionality using the command pattern in Go.
16 |
17 | ```go
18 | // Command interface
19 | type Command interface {
20 | Execute()
21 | Unexecute()
22 | }
23 |
24 | // Receiver
25 | type TextEditor struct {
26 | text string
27 | }
28 |
29 | func (t *TextEditor) Add(s string) {
30 | t.text += s
31 | }
32 |
33 | func (t *TextEditor) Delete(n int) {
34 | if n <= len(t.text) {
35 | t.text = t.text[:len(t.text)-n]
36 | }
37 | }
38 |
39 | func (t *TextEditor) Display() {
40 | fmt.Println(t.text)
41 | }
42 |
43 | // ConcreteCommand for Adding Text
44 | type AddTextCommand struct {
45 | editor *TextEditor
46 | text string
47 | }
48 |
49 | func (c *AddTextCommand) Execute() {
50 | c.editor.Add(c.text)
51 | }
52 |
53 | func (c *AddTextCommand) Unexecute() {
54 | c.editor.Delete(len(c.text))
55 | }
56 |
57 | // Invoker
58 | type CommandInvoker struct {
59 | history []Command
60 | }
61 |
62 | func (i *CommandInvoker) Execute(c Command) {
63 | c.Execute()
64 | i.history = append(i.history, c)
65 | }
66 |
67 | func (i *CommandInvoker) Undo() {
68 | if len(i.history) > 0 {
69 | lastCommand := i.history[len(i.history)-1]
70 | lastCommand.Unexecute()
71 | i.history = i.history[:len(i.history)-1]
72 | }
73 | }
74 | ```
75 |
76 | In this example, the text editor is our receiver, and we have a specific command for adding text (`AddTextCommand`) with both Execute and `Unexecute` methods. The invoker (`CommandInvoker`) manages the execution of commands and keeps a history of executed commands, allowing for simple undo functionality.
77 |
78 | By employing the command pattern, we've made it easy to extend the text editor with additional commands (like copy, paste, formatting) without changing existing code. The undo functionality is also neatly encapsulated within the invoker, allowing for more advanced features like multi-level undo or redo with minimal changes.
79 |
--------------------------------------------------------------------------------
/behavioral/command/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Command interface
6 | type Command interface {
7 | Execute()
8 | Unexecute()
9 | }
10 |
11 | // Receiver
12 | type TextEditor struct {
13 | text string
14 | }
15 |
16 | func (t *TextEditor) Add(s string) {
17 | t.text += s
18 | }
19 |
20 | func (t *TextEditor) Delete(n int) {
21 | if n <= len(t.text) {
22 | t.text = t.text[:len(t.text)-n]
23 | }
24 | }
25 |
26 | func (t *TextEditor) Display() {
27 | fmt.Println(t.text)
28 | }
29 |
30 | // ConcreteCommand for Adding Text
31 | type AddTextCommand struct {
32 | editor *TextEditor
33 | text string
34 | }
35 |
36 | func (c *AddTextCommand) Execute() {
37 | c.editor.Add(c.text)
38 | }
39 |
40 | func (c *AddTextCommand) Unexecute() {
41 | c.editor.Delete(len(c.text))
42 | }
43 |
44 | // Invoker
45 | type CommandInvoker struct {
46 | history []Command
47 | }
48 |
49 | func (i *CommandInvoker) Execute(c Command) {
50 | c.Execute()
51 | i.history = append(i.history, c)
52 | }
53 |
54 | func (i *CommandInvoker) Undo() {
55 | if len(i.history) > 0 {
56 | lastCommand := i.history[len(i.history)-1]
57 | lastCommand.Unexecute()
58 | i.history = i.history[:len(i.history)-1]
59 | }
60 | }
61 |
62 | func main() {
63 | editor := &TextEditor{}
64 | invoker := &CommandInvoker{}
65 |
66 | addCommand1 := &AddTextCommand{editor: editor, text: "Hello, "}
67 | invoker.Execute(addCommand1)
68 | editor.Display() // Output: Hello,
69 |
70 | addCommand2 := &AddTextCommand{editor: editor, text: "world!"}
71 | invoker.Execute(addCommand2)
72 | editor.Display() // Output: Hello, world!
73 |
74 | invoker.Undo()
75 | editor.Display() // Output: Hello,
76 | }
77 |
--------------------------------------------------------------------------------
/behavioral/interpreter/README.md:
--------------------------------------------------------------------------------
1 | # Interpreter
2 |
3 | The Interpreter design pattern is a behavioral design pattern that provides a way to evaluate language grammar for particular languages. It involves defining a representation for the language's grammar and an interpreter to interpret the grammar. The pattern is particularly useful for building compilers and interpreters, but it's generally less commonly used than other design patterns.
4 |
5 | ### Participants
6 |
7 | - **Abstract Expression**: Declares an abstract Interpret operation that is common to all nodes in the abstract syntax tree.
8 | - **Terminal Expression**: Implements the Interpret operation for terminal expressions.
9 | - **Nonterminal Expression**: Implements the Interpret operation for grammar rules which include other expressions.
10 | - **Context**: Contains the global information that is interpreted.
11 |
12 | ## Example
13 |
14 | Let's consider a simple arithmetic problem where we want to evaluate an expression given in Reverse Polish Notation (RPN). In RPN, every operator follows all of its operands. For example, the expression `3 4 +` evaluates to `7`.
15 |
16 | Here is how you can implement it in Go:
17 |
18 | ```go
19 | // Expression interface
20 | type Expression interface {
21 | Interpret() int
22 | }
23 |
24 | // TerminalExpression
25 | type Number struct {
26 | value int
27 | }
28 |
29 | func (n *Number) Interpret() int {
30 | return n.value
31 | }
32 |
33 | // NonTerminalExpression
34 | type Operation struct {
35 | left, right Expression
36 | operator string
37 | }
38 |
39 | func (o *Operation) Interpret() int {
40 | switch o.operator {
41 | case "+":
42 | return o.left.Interpret() + o.right.Interpret()
43 | case "-":
44 | return o.left.Interpret() - o.right.Interpret()
45 | case "*":
46 | return o.left.Interpret() * o.right.Interpret()
47 | case "/":
48 | return o.left.Interpret() / o.right.Interpret()
49 | }
50 | return 0
51 | }
52 |
53 | // Context
54 | type Context struct {
55 | stack []Expression
56 | }
57 |
58 | func (c *Context) Parse(tokens []string) Expression {
59 | for _, token := range tokens {
60 | if token == "+" || token == "-" || token == "*" || token == "/" {
61 | right := c.stack[len(c.stack)-1]
62 | c.stack = c.stack[:len(c.stack)-1]
63 | left := c.stack[len(c.stack)-1]
64 | c.stack = c.stack[:len(c.stack)-1]
65 |
66 | c.stack = append(c.stack, &Operation{
67 | left: left,
68 | right: right,
69 | operator: token,
70 | })
71 | } else {
72 | num, _ := strconv.Atoi(token)
73 | c.stack = append(c.stack, &Number{value: num})
74 | }
75 | }
76 | return c.stack[len(c.stack)-1]
77 | }
78 | ```
79 |
80 | In this example:
81 |
82 | - `Expression` is the Abstract Expression that declares an `Interpret()` method.
83 | - `Number` is a Terminal Expression that represents individual numbers.
84 | - `Operation` is a Non-terminal Expression that represents arithmetic operations.
85 | - `Context` stores the global information (in this case, the operand stack), and it also has a `Parse` method to build the abstract syntax tree for the given RPN expression.
86 |
87 |
88 | The Interpreter pattern lets you build a parse tree from your language of choice and then evaluate it. However, it's worth noting that this pattern can lead to a large number of classes and can be hard to manage for complex grammars. In such cases, alternative techniques such as parser combinators or parser generators may be more appropriate.
89 |
--------------------------------------------------------------------------------
/behavioral/interpreter/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "strconv"
6 | "strings"
7 | )
8 |
9 | // Expression interface
10 | type Expression interface {
11 | Interpret() int
12 | }
13 |
14 | // TerminalExpression
15 | type Number struct {
16 | value int
17 | }
18 |
19 | func (n *Number) Interpret() int {
20 | return n.value
21 | }
22 |
23 | // NonTerminalExpression
24 | type Operation struct {
25 | left, right Expression
26 | operator string
27 | }
28 |
29 | func (o *Operation) Interpret() int {
30 | switch o.operator {
31 | case "+":
32 | return o.left.Interpret() + o.right.Interpret()
33 | case "-":
34 | return o.left.Interpret() - o.right.Interpret()
35 | case "*":
36 | return o.left.Interpret() * o.right.Interpret()
37 | case "/":
38 | return o.left.Interpret() / o.right.Interpret()
39 | }
40 | return 0
41 | }
42 |
43 | // Context
44 | type Context struct {
45 | stack []Expression
46 | }
47 |
48 | func (c *Context) Parse(tokens []string) Expression {
49 | for _, token := range tokens {
50 | if token == "+" || token == "-" || token == "*" || token == "/" {
51 | right := c.stack[len(c.stack)-1]
52 | c.stack = c.stack[:len(c.stack)-1]
53 | left := c.stack[len(c.stack)-1]
54 | c.stack = c.stack[:len(c.stack)-1]
55 |
56 | c.stack = append(c.stack, &Operation{
57 | left: left,
58 | right: right,
59 | operator: token,
60 | })
61 | } else {
62 | num, _ := strconv.Atoi(token)
63 | c.stack = append(c.stack, &Number{value: num})
64 | }
65 | }
66 | return c.stack[len(c.stack)-1]
67 | }
68 |
69 | func main() {
70 | context := &Context{}
71 | expression := context.Parse(strings.Fields("3 4 + 2 * 7 /"))
72 |
73 | fmt.Println("Result:", expression.Interpret())
74 | }
75 |
--------------------------------------------------------------------------------
/behavioral/iterator/README.md:
--------------------------------------------------------------------------------
1 | # Iterator
2 |
3 | The "Iterator" design pattern provides a way to access the elements of an aggregate object (like a collection) sequentially without exposing its underlying representation. The main purpose of this pattern is to decouple the iteration logic from the collection itself.
4 |
5 | The Iterator pattern typically involves at least three components:
6 |
7 | - Iterator: This defines an interface for accessing and traversing elements.
8 | - ConcreteIterator: This implements the Iterator interface, keeping track of the current position in the traversal of the aggregate.
9 | - Aggregate: This defines an interface for creating an Iterator object.
10 | - ConcreteAggregate: This implements the Aggregate interface and returns an instance of the ConcreteIterator.
11 |
12 | ## Example
13 |
14 | Iterators are often used in real-world software systems to abstract the process of iterating over different types of collections. For a more practical example, let's consider a scenario where we have a software system managing different types of data sources. One common task might be to iterate over records from each data source, regardless of how that data is stored or represented.
15 |
16 | **Scenario**: Let's say you're building a system that manages user profiles. The profiles can be stored in different data structures: a slice (array-like structure in Go) and a map. You want to have a consistent way to iterate over user profiles, irrespective of the underlying data structure.
17 |
18 | **Implementation**:
19 |
20 | 1. **UserProfile**: Represents the user profile.
21 | 2. **Aggregate**: An interface to create an Iterator.
22 | 3. **Iterator**: Interface to traverse through elements.
23 |
24 | **Concrete Aggregates**:
25 | 1. **UserProfileSlice**: Represents a slice of user profiles.
26 | 2. **UserProfileMap**: Represents a map of user profiles.
27 |
28 | **Concrete Iterators**:
29 | 1. **SliceIterator**: Iterates over a slice.
30 | 2. **MapIterator**: Iterates over a map.
31 |
32 | Here's how you can implement the above:
33 |
34 | ```go
35 | type UserProfile struct {
36 | ID int
37 | Name string
38 | }
39 |
40 | // Aggregate interface
41 | type UserProfileCollection interface {
42 | CreateIterator() Iterator
43 | }
44 |
45 | // Iterator interface
46 | type Iterator interface {
47 | HasNext() bool
48 | Next() *UserProfile
49 | }
50 |
51 | // Concrete Aggregate: Slice
52 | type UserProfileSlice struct {
53 | profiles []UserProfile
54 | }
55 |
56 | func (us *UserProfileSlice) CreateIterator() Iterator {
57 | return &SliceIterator{profiles: us.profiles, index: 0}
58 | }
59 |
60 | type SliceIterator struct {
61 | profiles []UserProfile
62 | index int
63 | }
64 |
65 | func (si *SliceIterator) HasNext() bool {
66 | return si.index < len(si.profiles)
67 | }
68 |
69 | func (si *SliceIterator) Next() *UserProfile {
70 | if si.HasNext() {
71 | profile := &si.profiles[si.index]
72 | si.index++
73 | return profile
74 | }
75 | return nil
76 | }
77 |
78 | // Concrete Aggregate: Map
79 | type UserProfileMap struct {
80 | profiles map[int]UserProfile
81 | keys []int
82 | }
83 |
84 | func (um *UserProfileMap) CreateIterator() Iterator {
85 | keys := make([]int, 0, len(um.profiles))
86 | for k := range um.profiles {
87 | keys = append(keys, k)
88 | }
89 | return &MapIterator{profiles: um.profiles, keys: keys, index: 0}
90 | }
91 |
92 | type MapIterator struct {
93 | profiles map[int]UserProfile
94 | keys []int
95 | index int
96 | }
97 |
98 | func (mi *MapIterator) HasNext() bool {
99 | return mi.index < len(mi.keys)
100 | }
101 |
102 | func (mi *MapIterator) Next() *UserProfile {
103 | if mi.HasNext() {
104 | key := mi.keys[mi.index]
105 | profile := mi.profiles[key]
106 | mi.index++
107 | return &profile
108 | }
109 | return nil
110 | }
111 | ```
112 |
113 | The main advantage here is that the code iterating over user profiles remains the same, irrespective of whether the underlying data structure is a slice or a map. This decouples the iteration logic from the data structure, making the code more modular and easier to maintain.
114 |
--------------------------------------------------------------------------------
/behavioral/iterator/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type UserProfile struct {
6 | ID int
7 | Name string
8 | }
9 |
10 | // Aggregate interface
11 | type UserProfileCollection interface {
12 | CreateIterator() Iterator
13 | }
14 |
15 | // Iterator interface
16 | type Iterator interface {
17 | HasNext() bool
18 | Next() *UserProfile
19 | }
20 |
21 | // Concrete Aggregate: Slice
22 | type UserProfileSlice struct {
23 | profiles []UserProfile
24 | }
25 |
26 | func (us *UserProfileSlice) CreateIterator() Iterator {
27 | return &SliceIterator{profiles: us.profiles, index: 0}
28 | }
29 |
30 | type SliceIterator struct {
31 | profiles []UserProfile
32 | index int
33 | }
34 |
35 | func (si *SliceIterator) HasNext() bool {
36 | return si.index < len(si.profiles)
37 | }
38 |
39 | func (si *SliceIterator) Next() *UserProfile {
40 | if si.HasNext() {
41 | profile := &si.profiles[si.index]
42 | si.index++
43 | return profile
44 | }
45 | return nil
46 | }
47 |
48 | // Concrete Aggregate: Map
49 | type UserProfileMap struct {
50 | profiles map[int]UserProfile
51 | keys []int
52 | }
53 |
54 | func (um *UserProfileMap) CreateIterator() Iterator {
55 | keys := make([]int, 0, len(um.profiles))
56 | for k := range um.profiles {
57 | keys = append(keys, k)
58 | }
59 | return &MapIterator{profiles: um.profiles, keys: keys, index: 0}
60 | }
61 |
62 | type MapIterator struct {
63 | profiles map[int]UserProfile
64 | keys []int
65 | index int
66 | }
67 |
68 | func (mi *MapIterator) HasNext() bool {
69 | return mi.index < len(mi.keys)
70 | }
71 |
72 | func (mi *MapIterator) Next() *UserProfile {
73 | if mi.HasNext() {
74 | key := mi.keys[mi.index]
75 | profile := mi.profiles[key]
76 | mi.index++
77 | return &profile
78 | }
79 | return nil
80 | }
81 |
82 | func main() {
83 | sliceData := &UserProfileSlice{
84 | profiles: []UserProfile{
85 | {ID: 1, Name: "Alice"},
86 | {ID: 2, Name: "Bob"},
87 | },
88 | }
89 |
90 | mapData := &UserProfileMap{
91 | profiles: map[int]UserProfile{
92 | 3: {ID: 3, Name: "Charlie"},
93 | 4: {ID: 4, Name: "Dave"},
94 | },
95 | }
96 |
97 | // Iterating over slice
98 | iterator := sliceData.CreateIterator()
99 | fmt.Println("Iterating over slice:")
100 | for iterator.HasNext() {
101 | fmt.Println(iterator.Next())
102 | }
103 |
104 | // Iterating over map
105 | iterator = mapData.CreateIterator()
106 | fmt.Println("\nIterating over map:")
107 | for iterator.HasNext() {
108 | fmt.Println(iterator.Next())
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/behavioral/mediator/README.md:
--------------------------------------------------------------------------------
1 | # Mediator
2 |
3 | The Mediator design pattern is a behavioral design pattern that aims to reduce coupling between classes that communicate with each other. Instead of classes communicating directly with each other, they interact through a mediator object. This makes it easier to modify, add, or remove components without having to alter the other interacting components. The Mediator pattern is particularly useful in large and complex systems where you want to control the interactions between classes.
4 |
5 | ## Participants in the Mediator Pattern
6 |
7 | - **Mediator**: The interface that declares methods to communicate with Colleagues.
8 | - **ConcreteMediator**: Implements the Mediator interface and keeps track of all Colleagues.
9 | - **Colleague**: An interface for components that will communicate with each other via the Mediator.
10 | - **ConcreteColleague**: The class that will implement the Colleague interface and communicate via the Mediator.
11 |
12 | ## Example
13 |
14 | Let's consider a chat room as an example, where multiple users can send messages to the chat room, and the chat room will display the messages to all users.
15 |
16 | Here is a simple implementation in Go:
17 |
18 | ```go
19 | // Mediator interface
20 | type Mediator interface {
21 | SendMessage(string, Colleague)
22 | }
23 |
24 | // Colleague interface
25 | type Colleague interface {
26 | Send(string)
27 | Receive(string)
28 | }
29 |
30 | // ConcreteMediator
31 | type ChatRoom struct {
32 | users []Colleague
33 | }
34 |
35 | func (c *ChatRoom) Register(user Colleague) {
36 | c.users = append(c.users, user)
37 | }
38 |
39 | func (c *ChatRoom) SendMessage(message string, sender Colleague) {
40 | for _, user := range c.users {
41 | if user != sender {
42 | user.Receive(message)
43 | }
44 | }
45 | }
46 |
47 | // ConcreteColleague
48 | type User struct {
49 | name string
50 | chatMed Mediator
51 | }
52 |
53 | func NewUser(name string, chatMed Mediator) *User {
54 | return &User{name: name, chatMed: chatMed}
55 | }
56 |
57 | func (u *User) Send(message string) {
58 | fmt.Printf("%s sends message: %s\n", u.name, message)
59 | u.chatMed.SendMessage(message, u)
60 | }
61 |
62 | func (u *User) Receive(message string) {
63 | fmt.Printf("%s received message: %s\n", u.name, message)
64 | }
65 | ```
66 |
67 | In this example:
68 |
69 | - `Mediator` is represented by the `Mediator` interface, and `ChatRoom` is the `ConcreteMediator`.
70 | - `Colleague` is represented by the `Colleague` interface, and `User` is the `ConcreteColleague`.
71 |
72 | The `ChatRoom` keeps track of all `User` objects and handles the forwarding of messages between them. Each `User` communicates only with the `ChatRoom`, reducing the coupling between `User` objects.
73 |
--------------------------------------------------------------------------------
/behavioral/mediator/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Mediator interface
6 | type Mediator interface {
7 | SendMessage(string, Colleague)
8 | }
9 |
10 | // Colleague interface
11 | type Colleague interface {
12 | Send(string)
13 | Receive(string)
14 | }
15 |
16 | // ConcreteMediator
17 | type ChatRoom struct {
18 | users []Colleague
19 | }
20 |
21 | func (c *ChatRoom) Register(user Colleague) {
22 | c.users = append(c.users, user)
23 | }
24 |
25 | func (c *ChatRoom) SendMessage(message string, sender Colleague) {
26 | for _, user := range c.users {
27 | if user != sender {
28 | user.Receive(message)
29 | }
30 | }
31 | }
32 |
33 | // ConcreteColleague
34 | type User struct {
35 | name string
36 | chatMed Mediator
37 | }
38 |
39 | func NewUser(name string, chatMed Mediator) *User {
40 | return &User{name: name, chatMed: chatMed}
41 | }
42 |
43 | func (u *User) Send(message string) {
44 | fmt.Printf("%s sends message: %s\n", u.name, message)
45 | u.chatMed.SendMessage(message, u)
46 | }
47 |
48 | func (u *User) Receive(message string) {
49 | fmt.Printf("%s received message: %s\n", u.name, message)
50 | }
51 |
52 | func main() {
53 | chatroom := &ChatRoom{}
54 |
55 | alice := NewUser("Alice", chatroom)
56 | bob := NewUser("Bob", chatroom)
57 | charlie := NewUser("Charlie", chatroom)
58 |
59 | chatroom.Register(alice)
60 | chatroom.Register(bob)
61 | chatroom.Register(charlie)
62 |
63 | alice.Send("Hi, everyone!")
64 | bob.Send("Hello, Alice!")
65 | charlie.Send("Hey, how are you?")
66 | }
67 |
--------------------------------------------------------------------------------
/behavioral/memento/README.md:
--------------------------------------------------------------------------------
1 | # Memento
2 |
3 | The Memento design pattern is a behavioral design pattern that provides the capability to restore an object to its previous state. This pattern is particularly useful when you need to implement features like undo or save functionality. The pattern involves three types of participant classes:
4 |
5 | - **Originator**: The class that has an internal state we wish to save and restore later.
6 | - **Memento**: The class that stores the internal state of the Originator. The state could be saved outside the Originator but without exposing the details.
7 | - **Caretaker**: The class that keeps track of various states of the Originator. It keeps a list of Memento objects to achieve this.
8 |
9 | ## Example
10 |
11 | Let's implement the Memento pattern to maintain the history of a simple text editor, allowing us to undo changes.
12 |
13 | Here is the code in Go:
14 |
15 | ```go
16 | // Originator
17 | type Editor struct {
18 | text string
19 | }
20 |
21 | func (e *Editor) SetText(text string) {
22 | e.text = text
23 | }
24 |
25 | func (e *Editor) CreateSnapshot() *Snapshot {
26 | return &Snapshot{e.text}
27 | }
28 |
29 | func (e *Editor) RestoreSnapshot(s *Snapshot) {
30 | e.text = s.GetText()
31 | }
32 |
33 | // Memento
34 | type Snapshot struct {
35 | text string
36 | }
37 |
38 | func (s *Snapshot) GetText() string {
39 | return s.text
40 | }
41 |
42 | // Caretaker
43 | type History struct {
44 | snapshots []*Snapshot
45 | }
46 |
47 | func (h *History) AddSnapshot(s *Snapshot) {
48 | h.snapshots = append(h.snapshots, s)
49 | }
50 |
51 | func (h *History) Undo() *Snapshot {
52 | length := len(h.snapshots)
53 |
54 | if length < 2 {
55 | return nil // Cannot undo; not enough snapshots
56 | }
57 |
58 | lastSnapshot := h.snapshots[length-2] // Get the second last snapshot
59 | h.snapshots = h.snapshots[:length-1] // Remove the last snapshot
60 |
61 | return lastSnapshot // Return the second last snapshot
62 | }
63 | ```
64 |
65 | In this example:
66 |
67 | - `Editor` represents the `Originator`. It maintains some text and can produce snapshots (`Memento`) of its current state.
68 | - `Snapshot` represents the `Memento`. It stores a snapshot of the `Editor`'s state.
69 | - `History` is the `Caretaker`. It maintains a history of states that can be used to restore the `Editor` to previous states.
70 |
--------------------------------------------------------------------------------
/behavioral/memento/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Originator
6 | type Editor struct {
7 | text string
8 | }
9 |
10 | func (e *Editor) SetText(text string) {
11 | e.text = text
12 | }
13 |
14 | func (e *Editor) CreateSnapshot() *Snapshot {
15 | return &Snapshot{e.text}
16 | }
17 |
18 | func (e *Editor) RestoreSnapshot(s *Snapshot) {
19 | e.text = s.GetText()
20 | }
21 |
22 | // Memento
23 | type Snapshot struct {
24 | text string
25 | }
26 |
27 | func (s *Snapshot) GetText() string {
28 | return s.text
29 | }
30 |
31 | // Caretaker
32 | type History struct {
33 | snapshots []*Snapshot
34 | }
35 |
36 | func (h *History) AddSnapshot(s *Snapshot) {
37 | h.snapshots = append(h.snapshots, s)
38 | }
39 |
40 | func (h *History) Undo() *Snapshot {
41 | length := len(h.snapshots)
42 |
43 | if length < 2 {
44 | return nil // Cannot undo; not enough snapshots
45 | }
46 |
47 | lastSnapshot := h.snapshots[length-2] // Get the second last snapshot
48 | h.snapshots = h.snapshots[:length-1] // Remove the last snapshot
49 |
50 | return lastSnapshot // Return the second last snapshot
51 | }
52 |
53 | func main() {
54 | editor := &Editor{}
55 | history := &History{}
56 |
57 | editor.SetText("First line.")
58 | history.AddSnapshot(editor.CreateSnapshot())
59 |
60 | editor.SetText("Second line.")
61 | history.AddSnapshot(editor.CreateSnapshot())
62 |
63 | editor.SetText("Third line.")
64 | history.AddSnapshot(editor.CreateSnapshot())
65 |
66 | fmt.Println("Current Text:", editor.text)
67 |
68 | // Undo to previous state
69 | editor.RestoreSnapshot(history.Undo())
70 | fmt.Println("Undo 1: ", editor.text)
71 |
72 | // Undo to previous state
73 | editor.RestoreSnapshot(history.Undo())
74 | fmt.Println("Undo 2: ", editor.text)
75 |
76 | // Undo to previous state; As this is the last state, it should remain the same.
77 | snapshot := history.Undo()
78 | if snapshot != nil {
79 | editor.RestoreSnapshot(snapshot)
80 | }
81 | fmt.Println("Undo 3: ", editor.text)
82 | }
83 |
--------------------------------------------------------------------------------
/behavioral/observer/README.md:
--------------------------------------------------------------------------------
1 | # Observer
2 |
3 | The Observer Design Pattern is a behavioral design pattern that allows objects to notify other objects about changes in their state. It establishes a one-to-many dependency between a subject object that holds state, and any number of observer objects that are interested in changes to the subject's state.
4 |
5 | Here's a simple analogy: think of a news publisher and its subscribers. When the publisher releases a new article, it notifies all its subscribers. In this scenario, the publisher is the "subject" and the subscribers are the "observers". This concept of automatically notifying interested parties is the core idea behind the Observer pattern.
6 |
7 | In software, the Observer pattern is commonly used in event-driven systems. You would use the Observer pattern when changes to the state of one object may require changes in other objects, and the actual number of objects is unknown or dynamic.
8 |
9 | Here's a high-level description of the Observer pattern's participants:
10 |
11 | - Subject: This is the object that holds the state. It allows observers to register and unregister their interest.
12 |
13 | - Observer: These are the objects that want to know about changes. They register their interest with the Subject and also define a method for receiving notifications.
14 |
15 | - ConcreteSubject: A concrete subject stores the state of interest to ConcreteObserver objects. When a change occurs in the subject's state, it sends a notification to all registered Observers.
16 |
17 | - ConcreteObserver: A ConcreteObserver maintains a reference to a ConcreteSubject object, stores state that should stay consistent with the subject's, and implements the Observer updating interface to keep its state consistent with the subject's.
18 |
19 | In Go, this pattern could be implemented using interfaces to define the `Subject` and `Observer`, and individual types that implement these interfaces. The Observer's update method would be called when the `Subject` changes.
20 |
21 | ## Example
22 |
23 | Let's consider a scenario where we have a Job Posting site and users can subscribe to be notified when a new job is posted. This is a good example for the Observer pattern as it involves a subject (Job Postings) and observers (Subscribed Users) where observers need to be notified when there's a change in the subject.
24 |
25 | ```go
26 | // JobPost is a struct that represents a job posting
27 | type JobPost struct {
28 | title string
29 | }
30 |
31 | // Observer interface
32 | type Observer interface {
33 | Notify(jobPost JobPost)
34 | }
35 |
36 | // JobSeeker implements Observer
37 | type JobSeeker struct {
38 | name string
39 | }
40 |
41 | func (js *JobSeeker) Notify(jobPost JobPost) {
42 | fmt.Printf("Hi %s! New job posted: %s\n", js.name, jobPost.title)
43 | }
44 |
45 | // JobBoard is our subject struct
46 | type JobBoard struct {
47 | subscribers []Observer
48 | }
49 |
50 | func (jb *JobBoard) Subscribe(observer Observer) {
51 | jb.subscribers = append(jb.subscribers, observer)
52 | }
53 |
54 | func (jb *JobBoard) AddJob(jobPost JobPost) {
55 | for _, subscriber := range jb.subscribers {
56 | subscriber.Notify(jobPost)
57 | }
58 | }
59 | ```
60 |
61 | When a new job is posted (i.e., the JobBoard's state changes), all the subscribed job seekers are notified. This is the Observer pattern in action.
62 |
--------------------------------------------------------------------------------
/behavioral/observer/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // JobPost is a struct that represents a job posting
6 | type JobPost struct {
7 | title string
8 | }
9 |
10 | // Observer interface
11 | type Observer interface {
12 | Notify(jobPost JobPost)
13 | }
14 |
15 | // JobSeeker implements Observer
16 | type JobSeeker struct {
17 | name string
18 | }
19 |
20 | func (js *JobSeeker) Notify(jobPost JobPost) {
21 | fmt.Printf("Hi %s! New job posted: %s\n", js.name, jobPost.title)
22 | }
23 |
24 | // JobBoard is our subject struct
25 | type JobBoard struct {
26 | subscribers []Observer
27 | }
28 |
29 | func (jb *JobBoard) Subscribe(observer Observer) {
30 | jb.subscribers = append(jb.subscribers, observer)
31 | }
32 |
33 | func (jb *JobBoard) AddJob(jobPost JobPost) {
34 | for _, subscriber := range jb.subscribers {
35 | subscriber.Notify(jobPost)
36 | }
37 | }
38 |
39 | func main() {
40 | // Create subscribers
41 | jobSeeker1 := &JobSeeker{name: "John Doe"}
42 | jobSeeker2 := &JobSeeker{name: "Jane Doe"}
43 |
44 | // Create publisher and add subscribers
45 | jobBoard := &JobBoard{}
46 | jobBoard.Subscribe(jobSeeker1)
47 | jobBoard.Subscribe(jobSeeker2)
48 |
49 | // Add a new job and see if subscribers get notified
50 | jobBoard.AddJob(JobPost{"Software Engineer"})
51 | }
52 |
--------------------------------------------------------------------------------
/behavioral/state/README.md:
--------------------------------------------------------------------------------
1 | # State
2 |
3 | The "state" design pattern allows an object to change its behavior when its internal state changes. In essence, it appears as if the object changed its class. Instead of having a monolithic object that tries to manage every possible state through conditionals or switch statements, the state pattern promotes the idea of encapsulating state-specific behavior into separate state classes.
4 |
5 | Let's look at a basic breakdown:
6 |
7 | - State Interface: Defines an interface to encapsulate the associated behaviors with a particular state of the Context.
8 | - Concrete States: Classes that implement the State interface and provide the behavior specific to a state.
9 | - Context: The main object whose behavior changes based on its current state.
10 |
11 | ## Example
12 |
13 | Let's consider the scenario of an online order system where an order can be in various states, like New, Shipped, Delivered, or Canceled. Depending on the current state of an order, the operations you can perform on it and the transitions to other states might differ.
14 |
15 | ```go
16 | // State interface
17 | type OrderState interface {
18 | ShipOrder()
19 | DeliverOrder()
20 | CancelOrder()
21 | }
22 |
23 | // Concrete States
24 | type NewOrderState struct{}
25 |
26 | func (n *NewOrderState) ShipOrder() {
27 | fmt.Println("Shipping Order.")
28 | }
29 |
30 | func (n *NewOrderState) DeliverOrder() {
31 | fmt.Println("Can't deliver an order which hasn't been shipped!")
32 | }
33 |
34 | func (n *NewOrderState) CancelOrder() {
35 | fmt.Println("Canceling Order.")
36 | }
37 |
38 | type ShippedOrderState struct{}
39 |
40 | func (s *ShippedOrderState) ShipOrder() {
41 | fmt.Println("Can't ship an order again.")
42 | }
43 |
44 | func (s *ShippedOrderState) DeliverOrder() {
45 | fmt.Println("Delivering Order.")
46 | }
47 |
48 | func (s *ShippedOrderState) CancelOrder() {
49 | fmt.Println("Can't cancel a shipped order!")
50 | }
51 |
52 | type DeliveredOrderState struct{}
53 |
54 | func (d *DeliveredOrderState) ShipOrder() {
55 | fmt.Println("Order already delivered.")
56 | }
57 |
58 | func (d *DeliveredOrderState) DeliverOrder() {
59 | fmt.Println("Order already delivered.")
60 | }
61 |
62 | func (d *DeliveredOrderState) CancelOrder() {
63 | fmt.Println("Can't cancel a delivered order!")
64 | }
65 |
66 | // Context
67 | type Order struct {
68 | state OrderState
69 | }
70 |
71 | func (o *Order) ShipOrder() {
72 | o.state.ShipOrder()
73 | }
74 |
75 | func (o *Order) DeliverOrder() {
76 | o.state.DeliverOrder()
77 | }
78 |
79 | func (o *Order) CancelOrder() {
80 | o.state.CancelOrder()
81 | }
82 |
83 | func NewOrder() *Order {
84 | return &Order{state: &NewOrderState{}}
85 | }
86 | ```
87 |
88 | In this example, the `Order` context delegates all its actions to the current state. Each state class handles its respective logic. If a new state or behavior is introduced, we only need to add or modify the corresponding state class, keeping the `Order` context and other states untouched. This makes the system more maintainable and less error-prone.
89 |
--------------------------------------------------------------------------------
/behavioral/state/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // State interface
6 | type OrderState interface {
7 | ShipOrder()
8 | DeliverOrder()
9 | CancelOrder()
10 | }
11 |
12 | // Concrete States
13 | type NewOrderState struct{}
14 |
15 | func (n *NewOrderState) ShipOrder() {
16 | fmt.Println("Shipping Order.")
17 | }
18 |
19 | func (n *NewOrderState) DeliverOrder() {
20 | fmt.Println("Can't deliver an order which hasn't been shipped!")
21 | }
22 |
23 | func (n *NewOrderState) CancelOrder() {
24 | fmt.Println("Canceling Order.")
25 | }
26 |
27 | type ShippedOrderState struct{}
28 |
29 | func (s *ShippedOrderState) ShipOrder() {
30 | fmt.Println("Can't ship an order again.")
31 | }
32 |
33 | func (s *ShippedOrderState) DeliverOrder() {
34 | fmt.Println("Delivering Order.")
35 | }
36 |
37 | func (s *ShippedOrderState) CancelOrder() {
38 | fmt.Println("Can't cancel a shipped order!")
39 | }
40 |
41 | type DeliveredOrderState struct{}
42 |
43 | func (d *DeliveredOrderState) ShipOrder() {
44 | fmt.Println("Order already delivered.")
45 | }
46 |
47 | func (d *DeliveredOrderState) DeliverOrder() {
48 | fmt.Println("Order already delivered.")
49 | }
50 |
51 | func (d *DeliveredOrderState) CancelOrder() {
52 | fmt.Println("Can't cancel a delivered order!")
53 | }
54 |
55 | // Context
56 | type Order struct {
57 | state OrderState
58 | }
59 |
60 | func (o *Order) ShipOrder() {
61 | o.state.ShipOrder()
62 | }
63 |
64 | func (o *Order) DeliverOrder() {
65 | o.state.DeliverOrder()
66 | }
67 |
68 | func (o *Order) CancelOrder() {
69 | o.state.CancelOrder()
70 | }
71 |
72 | func NewOrder() *Order {
73 | return &Order{state: &NewOrderState{}}
74 | }
75 |
76 | func main() {
77 | order := NewOrder()
78 | order.ShipOrder()
79 | order.DeliverOrder()
80 |
81 | // Setting a new state manually just for demonstration.
82 | order.state = &ShippedOrderState{}
83 | order.CancelOrder()
84 | }
85 |
--------------------------------------------------------------------------------
/behavioral/strategy/README.md:
--------------------------------------------------------------------------------
1 | # Strategy
2 |
3 | The Strategy design pattern is a behavioral design pattern that lets the algorithm vary independently from the clients that use it. It defines a family of algorithms, encapsulates each one, and makes them interchangeable.
4 |
5 | The strategy pattern involves using an interface to abstractly define an operation that needs to be carried out. Concrete implementations of the interface will encapsulate different strategies or ways to carry out the operation.
6 |
7 | The object that uses the strategy pattern will maintain a reference to a Strategy object and will communicate with this object only through the strategy interface.
8 |
9 | The advantage of the strategy pattern is that it promotes algorithmic independence. It decouples the behavior of an object from the object itself.
10 |
11 | Here's the general structure of Strategy design pattern:
12 |
13 | - Strategy (interface): This is an interface used to abstractly define the operation(s) that we're planning to implement with different strategies.
14 |
15 | - ConcreteStrategy (class): This is a class that implements the Strategy interface, providing its own version of the interface method(s).
16 |
17 | - Context (class): This is a class that uses a strategy to do something. It interacts with a strategy through the Strategy interface only, meaning it's decoupled from the ConcreteStrategy.
18 |
19 | This pattern can be beneficial when we need to select an algorithm at runtime. It's also helpful when we have a lot of similar classes that only differ in their behaviors. Instead of implementing many versions of your class with different behaviors, you can separate the behaviors as strategies and use the same context class in all versions.
20 |
21 | ## Example
22 |
23 | Let's use the Strategy pattern to select between a Bubble sort and a Quick sort strategy at runtime:
24 |
25 | ```go
26 | // SortStrategy defines the method for sorting
27 | type SortStrategy interface {
28 | Sort([]int) []int
29 | }
30 |
31 | // BubbleSortStrategy uses bubble sort algorithm for sorting
32 | type BubbleSortStrategy struct{}
33 |
34 | func (b *BubbleSortStrategy) Sort(input []int) []int {
35 | n := len(input)
36 | sorted := make([]int, n)
37 | copy(sorted, input)
38 |
39 | for i := 0; i < n; i++ {
40 | for j := 0; j < n-i-1; j++ {
41 | if sorted[j] > sorted[j+1] {
42 | sorted[j], sorted[j+1] = sorted[j+1], sorted[j]
43 | }
44 | }
45 | }
46 |
47 | return sorted
48 | }
49 |
50 | // QuickSortStrategy uses quick sort algorithm for sorting
51 | type QuickSortStrategy struct{}
52 |
53 | func (q *QuickSortStrategy) Sort(input []int) []int {
54 | sorted := make([]int, len(input))
55 | copy(sorted, input)
56 | sort.Ints(sorted)
57 | return sorted
58 | }
59 |
60 | // SortingContext is the context that uses the strategy
61 | type SortingContext struct {
62 | strategy SortStrategy
63 | }
64 |
65 | func (s *SortingContext) SetStrategy(strategy SortStrategy) {
66 | s.strategy = strategy
67 | }
68 |
69 | func (s *SortingContext) ExecuteStrategy(input []int) []int {
70 | return s.strategy.Sort(input)
71 | }
72 | ```
73 |
74 | In the example above, `SortStrategy` is the strategy interface, `BubbleSortStrategy` and `QuickSortStrategy` are concrete strategies, and `SortingContext` is the context. Depending on what we set as the `SortStrategy`, the appropriate sorting algorithm will be applied.
75 |
--------------------------------------------------------------------------------
/behavioral/strategy/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sort"
6 | )
7 |
8 | // SortStrategy defines the method for sorting
9 | type SortStrategy interface {
10 | Sort([]int) []int
11 | }
12 |
13 | // BubbleSortStrategy uses bubble sort algorithm for sorting
14 | type BubbleSortStrategy struct{}
15 |
16 | func (b *BubbleSortStrategy) Sort(input []int) []int {
17 | n := len(input)
18 | sorted := make([]int, n)
19 | copy(sorted, input)
20 |
21 | for i := 0; i < n; i++ {
22 | for j := 0; j < n-i-1; j++ {
23 | if sorted[j] > sorted[j+1] {
24 | sorted[j], sorted[j+1] = sorted[j+1], sorted[j]
25 | }
26 | }
27 | }
28 |
29 | return sorted
30 | }
31 |
32 | // QuickSortStrategy uses quick sort algorithm for sorting
33 | type QuickSortStrategy struct{}
34 |
35 | func (q *QuickSortStrategy) Sort(input []int) []int {
36 | sorted := make([]int, len(input))
37 | copy(sorted, input)
38 | sort.Ints(sorted)
39 | return sorted
40 | }
41 |
42 | // SortingContext is the context that uses the strategy
43 | type SortingContext struct {
44 | strategy SortStrategy
45 | }
46 |
47 | func (s *SortingContext) SetStrategy(strategy SortStrategy) {
48 | s.strategy = strategy
49 | }
50 |
51 | func (s *SortingContext) ExecuteStrategy(input []int) []int {
52 | return s.strategy.Sort(input)
53 | }
54 |
55 | func main() {
56 | data := []int{64, 34, 25, 12, 22, 11, 90}
57 | context := &SortingContext{}
58 |
59 | context.SetStrategy(&BubbleSortStrategy{})
60 | sortedData := context.ExecuteStrategy(data)
61 | fmt.Println("Bubble Sorted Data: ", sortedData)
62 |
63 | context.SetStrategy(&QuickSortStrategy{})
64 | sortedData = context.ExecuteStrategy(data)
65 | fmt.Println("Quick Sorted Data: ", sortedData)
66 | }
67 |
--------------------------------------------------------------------------------
/behavioral/template/README.md:
--------------------------------------------------------------------------------
1 | # Template
2 |
3 | The "Template" design pattern defines the program skeleton of an algorithm in an algorithm class but delays some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure.
4 |
5 | Basically, the pattern involves two main components:
6 |
7 | - Abstract Class: Defines abstract placeholder operations (primitive operations), concrete operations, and a template method.
8 | - Concrete Class: Implements the placeholder operations.
9 |
10 | The template method in the abstract class defines the structure of an algorithm and calls placeholder operations as well as concrete operations.
11 |
12 | ## Example
13 |
14 | The Template pattern is especially useful in software development scenarios where there's a clear sequence of steps to be performed, but the specifics of each step might vary.
15 |
16 | Consider the example of a build tool for various project types. Suppose there's a general sequence of steps for building a software project:
17 |
18 | - Load configuration.
19 | - Fetch dependencies.
20 | - Compile source code.
21 | - Run tests.
22 | - Package for deployment.
23 | - While the sequence remains consistent, the specifics of each step can vary depending on the project type (e.g., a Java project vs. a Go project).
24 |
25 | Let's demonstrate this with the Template pattern in Go:
26 |
27 | ```go
28 | // BuildProcess defines the steps of building a software project
29 | type BuildProcess interface {
30 | LoadConfiguration()
31 | FetchDependencies()
32 | Compile()
33 | RunTests()
34 | Package()
35 | }
36 |
37 | // The template method
38 | func Build(p BuildProcess) {
39 | p.LoadConfiguration()
40 | p.FetchDependencies()
41 | p.Compile()
42 | p.RunTests()
43 | p.Package()
44 | }
45 |
46 | type JavaProject struct{}
47 |
48 | func (j *JavaProject) LoadConfiguration() {
49 | fmt.Println("Loading Maven configuration...")
50 | }
51 |
52 | func (j *JavaProject) FetchDependencies() {
53 | fmt.Println("Fetching Maven dependencies...")
54 | }
55 |
56 | func (j *JavaProject) Compile() {
57 | fmt.Println("Compiling Java source files...")
58 | }
59 |
60 | func (j *JavaProject) RunTests() {
61 | fmt.Println("Running JUnit tests...")
62 | }
63 |
64 | func (j *JavaProject) Package() {
65 | fmt.Println("Packaging into a JAR file...")
66 | }
67 |
68 | type GoProject struct{}
69 |
70 | func (g *GoProject) LoadConfiguration() {
71 | fmt.Println("Loading Go modules configuration...")
72 | }
73 |
74 | func (g *GoProject) FetchDependencies() {
75 | fmt.Println("Fetching Go dependencies...")
76 | }
77 |
78 | func (g *GoProject) Compile() {
79 | fmt.Println("Building Go binary...")
80 | }
81 |
82 | func (g *GoProject) RunTests() {
83 | fmt.Println("Running Go tests...")
84 | }
85 |
86 | func (g *GoProject) Package() {
87 | fmt.Println("Packaging Go binary for deployment...")
88 | }
89 | ```
90 |
91 | In this example:
92 |
93 | - BuildProcess serves as our "abstract class", defining the sequence for building software projects.
94 | - Build is our template method, defining the standard order in which these methods should be called.
95 | - JavaProject and GoProject are our concrete classes, implementing the steps of the build process for Java and Go projects, respectively.
96 |
97 | This design makes it easy to introduce a build process for a new language or framework. Just implement the BuildProcess interface for the new project type and let the Build function handle the sequence.
98 |
--------------------------------------------------------------------------------
/behavioral/template/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // BuildProcess defines the steps of building a software project
6 | type BuildProcess interface {
7 | LoadConfiguration()
8 | FetchDependencies()
9 | Compile()
10 | RunTests()
11 | Package()
12 | }
13 |
14 | // The template method
15 | func Build(p BuildProcess) {
16 | p.LoadConfiguration()
17 | p.FetchDependencies()
18 | p.Compile()
19 | p.RunTests()
20 | p.Package()
21 | }
22 |
23 | type JavaProject struct{}
24 |
25 | func (j *JavaProject) LoadConfiguration() {
26 | fmt.Println("Loading Maven configuration...")
27 | }
28 |
29 | func (j *JavaProject) FetchDependencies() {
30 | fmt.Println("Fetching Maven dependencies...")
31 | }
32 |
33 | func (j *JavaProject) Compile() {
34 | fmt.Println("Compiling Java source files...")
35 | }
36 |
37 | func (j *JavaProject) RunTests() {
38 | fmt.Println("Running JUnit tests...")
39 | }
40 |
41 | func (j *JavaProject) Package() {
42 | fmt.Println("Packaging into a JAR file...")
43 | }
44 |
45 | type GoProject struct{}
46 |
47 | func (g *GoProject) LoadConfiguration() {
48 | fmt.Println("Loading Go modules configuration...")
49 | }
50 |
51 | func (g *GoProject) FetchDependencies() {
52 | fmt.Println("Fetching Go dependencies...")
53 | }
54 |
55 | func (g *GoProject) Compile() {
56 | fmt.Println("Building Go binary...")
57 | }
58 |
59 | func (g *GoProject) RunTests() {
60 | fmt.Println("Running Go tests...")
61 | }
62 |
63 | func (g *GoProject) Package() {
64 | fmt.Println("Packaging Go binary for deployment...")
65 | }
66 |
67 | func main() {
68 | java := &JavaProject{}
69 | Build(java)
70 |
71 | fmt.Println("---")
72 |
73 | golang := &GoProject{}
74 | Build(golang)
75 | }
76 |
--------------------------------------------------------------------------------
/behavioral/visitor/README.md:
--------------------------------------------------------------------------------
1 | # Visitor
2 |
3 | The Visitor design pattern is a behavioral design pattern that allows you to add further operations to objects without modifying the classes of the objects you're working with. It allows you to define a new operation without altering the classes of the elements on which it operates. This pattern can be particularly useful when dealing with a structure composed of a mixture of different types of objects and you want to perform operations that depend on the concrete classes of these objects.
4 |
5 | ### Participants
6 |
7 | - **Visitor**: This is an interface that declares a visit operation for each type of concrete element in the object structure.
8 | - **ConcreteVisitor**: This class implements the Visitor interface and defines the operations to be performed on each type of element.
9 | - **Element**: This is an interface that declares an `Accept` method that accepts a visitor.
10 | - **ConcreteElement**: This class implements the Element interface and allows the visitor to visit it.
11 |
12 | ## Example
13 |
14 | The Visitor pattern is often used in cases where you have a complex data structure, like an Abstract Syntax Tree (AST) in a compiler, or a Document Object Model (DOM) in a web browser. The Visitor pattern allows you to extend functionalities without modifying these structures.
15 |
16 | An Abstract Syntax Tree (AST) is a tree representation of the syntactic structure of source code written in a programming language. Each node in the tree denotes a construct in the language. It's "abstract" in the sense that it omits certain syntax rules that aren't necessary for understanding the program's structure. For example, grouping parentheses might be omitted because the structure of the tree makes the execution order of operations clear.
17 |
18 | ### Components
19 |
20 | - **Node**: Each node represents a language construct. For example, a node could represent an arithmetic operation like addition, a control flow construct like a `for` loop, or a data construct like an array.
21 |
22 | - **Edge**: Edges in an AST represent the relationship between the nodes. For example, an edge from an "If statement" node to a "Boolean expression" node signifies that the Boolean expression is a condition for the If statement.
23 |
24 | - **Root**: The root of the tree represents the entire program or the start symbol in the grammar of the programming language.
25 |
26 | ### Use Cases
27 |
28 | 1. **Compilers**: The front end of a compiler usually transforms source code into an AST as an intermediate step in translating code into machine language or bytecode.
29 |
30 | 2. **Code Analysis**: Tools that perform static code analysis often use ASTs to understand the structure of the code.
31 |
32 | 3. **Refactoring**: Code refactoring tools use ASTs to accurately transform the structure of the code.
33 |
34 | 4. **Syntax Highlighting**: Some advanced text editors use ASTs for better syntax highlighting.
35 |
36 |
37 | Consider a simple arithmetic expression `1 + 2 * 3`. An AST representing this expression might look like this:
38 |
39 | ```
40 | [+]
41 | / \
42 | [1] [*]
43 | / \
44 | [2] [3]
45 | ```
46 |
47 | Here, the root node represents the `+` operation. The left child is `1` and the right child is another operation `*`. This tree structure makes it clear that `2 * 3` should be evaluated first, and then added to `1`, adhering to the rules of arithmetic.
48 |
49 | Let's consider a simplified version of an AST. Assume that we have two types of expressions: `Literal` expressions (just numbers) and `Addition` expressions (which add two other expressions together). Now, imagine we want to perform multiple operations on these expressions: evaluate them to get a result and convert them to a string in infix notation.
50 |
51 | Here's how you could use the Visitor pattern to implement this in Go:
52 |
53 | ```go
54 | // Expression is the 'Element' interface
55 | type Expression interface {
56 | Accept(Visitor) string
57 | }
58 |
59 | // Visitor interface
60 | type Visitor interface {
61 | VisitLiteral(*Literal) string
62 | VisitAddition(*Addition) string
63 | }
64 |
65 | // Literal is a 'ConcreteElement'
66 | type Literal struct {
67 | value int
68 | }
69 |
70 | func (l *Literal) Accept(visitor Visitor) string {
71 | return visitor.VisitLiteral(l)
72 | }
73 |
74 | // Addition is another 'ConcreteElement'
75 | type Addition struct {
76 | left, right Expression
77 | }
78 |
79 | func (a *Addition) Accept(visitor Visitor) string {
80 | return visitor.VisitAddition(a)
81 | }
82 |
83 | // Evaluator is a 'ConcreteVisitor' that evaluates expressions
84 | type Evaluator struct{}
85 |
86 | func (e *Evaluator) VisitLiteral(l *Literal) string {
87 | return strconv.Itoa(l.value)
88 | }
89 |
90 | func (e *Evaluator) VisitAddition(a *Addition) string {
91 | left := a.left.Accept(e)
92 | right := a.right.Accept(e)
93 | return fmt.Sprintf("(%s + %s)", left, right)
94 | }
95 |
96 | // Renderer is another 'ConcreteVisitor' that converts expressions to strings
97 | type Renderer struct{}
98 |
99 | func (r *Renderer) VisitLiteral(l *Literal) string {
100 | return strconv.Itoa(l.value)
101 | }
102 |
103 | func (r *Renderer) VisitAddition(a *Addition) string {
104 | left := a.left.Accept(r)
105 | right := a.right.Accept(r)
106 | return fmt.Sprintf("(%s + %s)", left, right)
107 | }
108 | ```
109 |
110 | In this example:
111 |
112 | - `Expression` is the Element interface that declares an `Accept` method to accept a visitor.
113 | - `Literal` and `Addition` are Concrete Elements that represent literal numbers and addition operations, respectively.
114 | - `Visitor` is the Visitor interface that declares `VisitLiteral` and `VisitAddition` methods.
115 | - `Evaluator` and `Renderer` are Concrete Visitors. `Evaluator` evaluates expressions, and `Renderer` converts them to strings.
116 |
117 | This example is a simplified AST, but the Visitor pattern makes it easy to add new operations (like optimization, code generation, etc.) without changing the `Expression`, `Literal`, or `Addition` classes. It's particularly useful in software engineering scenarios like compilers and data transformation pipelines.
118 |
--------------------------------------------------------------------------------
/behavioral/visitor/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "strconv"
6 | )
7 |
8 | // Expression is the 'Element' interface
9 | type Expression interface {
10 | Accept(Visitor) string
11 | }
12 |
13 | // Visitor interface
14 | type Visitor interface {
15 | VisitLiteral(*Literal) string
16 | VisitAddition(*Addition) string
17 | }
18 |
19 | // Literal is a 'ConcreteElement'
20 | type Literal struct {
21 | value int
22 | }
23 |
24 | func (l *Literal) Accept(visitor Visitor) string {
25 | return visitor.VisitLiteral(l)
26 | }
27 |
28 | // Addition is another 'ConcreteElement'
29 | type Addition struct {
30 | left, right Expression
31 | }
32 |
33 | func (a *Addition) Accept(visitor Visitor) string {
34 | return visitor.VisitAddition(a)
35 | }
36 |
37 | // Evaluator is a 'ConcreteVisitor' that evaluates expressions
38 | type Evaluator struct{}
39 |
40 | func (e *Evaluator) VisitLiteral(l *Literal) string {
41 | return strconv.Itoa(l.value)
42 | }
43 |
44 | func (e *Evaluator) VisitAddition(a *Addition) string {
45 | left := a.left.Accept(e)
46 | right := a.right.Accept(e)
47 | return fmt.Sprintf("(%s + %s)", left, right)
48 | }
49 |
50 | // Renderer is another 'ConcreteVisitor' that converts expressions to strings
51 | type Renderer struct{}
52 |
53 | func (r *Renderer) VisitLiteral(l *Literal) string {
54 | return strconv.Itoa(l.value)
55 | }
56 |
57 | func (r *Renderer) VisitAddition(a *Addition) string {
58 | left := a.left.Accept(r)
59 | right := a.right.Accept(r)
60 | return fmt.Sprintf("(%s + %s)", left, right)
61 | }
62 |
63 | func main() {
64 | // Create an AST for the expression: (1 + (2 + 3))
65 | expression := &Addition{
66 | left: &Literal{value: 1},
67 | right: &Addition{left: &Literal{value: 2}, right: &Literal{value: 3}},
68 | }
69 |
70 | // Evaluate the expression
71 | evaluator := &Evaluator{}
72 | result := expression.Accept(evaluator)
73 | fmt.Printf("Evaluation: %s\n", result)
74 |
75 | // Render the expression
76 | renderer := &Renderer{}
77 | result = expression.Accept(renderer)
78 | fmt.Printf("Rendering: %s\n", result)
79 | }
80 |
--------------------------------------------------------------------------------
/creational/abstract_factory/README.md:
--------------------------------------------------------------------------------
1 | # Abstract factory
2 |
3 | The Abstract Factory Design Pattern is a creational pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes.
4 |
5 | In other words, an abstract factory is a factory of factories. With this pattern, a high level interface is provided that encapsulates a group of factories which share common themes without specifying concrete classes. These factories produce families of related products.
6 |
7 | This pattern is typically implemented via a master factory (the abstract factory) which is capable of creating other factories, which in turn, produce products within the same family.
8 |
9 | # Example
10 |
11 | Imagine we have a UI library, and we want it to support multiple themes (like Light and Dark). Different themes have different styles for the same type of components (like buttons, menus, etc.).
12 |
13 | ```go
14 | // Abstract product
15 | type Button interface {
16 | Render() string
17 | }
18 |
19 | // Concrete product: LightButton
20 | type LightButton struct{}
21 |
22 | func (b LightButton) Render() string {
23 | return "Rendering light theme button."
24 | }
25 |
26 | // Concrete product: DarkButton
27 | type DarkButton struct{}
28 |
29 | func (b DarkButton) Render() string {
30 | return "Rendering dark theme button."
31 | }
32 |
33 | // Abstract factory
34 | type UIFactory interface {
35 | CreateButton() Button
36 | }
37 |
38 | // Concrete factory: LightThemeFactory
39 | type LightThemeFactory struct{}
40 |
41 | func (f LightThemeFactory) CreateButton() Button {
42 | return LightButton{}
43 | }
44 |
45 | // Concrete factory: DarkThemeFactory
46 | type DarkThemeFactory struct{}
47 |
48 | func (f DarkThemeFactory) CreateButton() Button {
49 | return DarkButton{}
50 | }
51 | ```
52 |
53 | Here, `UIFactory` is the abstract factory. `LightThemeFactory` and `DarkThemeFactory` are its concrete factories. `Button` is the abstract product. `LightButton` and `DarkButton` are its concrete products.
54 |
55 | We can add more methods to the UIFactory to create other types of UI components (like `CreateMenu`, `CreateToolbar`, etc.), and more themes by adding more concrete factories.
56 |
57 | This pattern is especially useful when a system should be independent of how its products are created, composed, and represented, and when a family of related product objects is designed to be used together.
58 |
--------------------------------------------------------------------------------
/creational/abstract_factory/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Button interface {
8 | Render() string
9 | }
10 |
11 | type LightButton struct{}
12 |
13 | func (b LightButton) Render() string {
14 | return "Rendering light theme button."
15 | }
16 |
17 | type DarkButton struct{}
18 |
19 | func (b DarkButton) Render() string {
20 | return "Rendering dark theme button."
21 | }
22 |
23 | type UIFactory interface {
24 | CreateButton() Button
25 | }
26 |
27 | type LightThemeFactory struct{}
28 |
29 | func (f LightThemeFactory) CreateButton() Button {
30 | return LightButton{}
31 | }
32 |
33 | type DarkThemeFactory struct{}
34 |
35 | func (f DarkThemeFactory) CreateButton() Button {
36 | return DarkButton{}
37 | }
38 |
39 | func main() {
40 | var factory UIFactory
41 | var button Button
42 |
43 | // Select the factory based on user preference or config file, for example:
44 | userPrefersDarkMode := true // Imagine this value is from user settings
45 |
46 | if userPrefersDarkMode {
47 | factory = DarkThemeFactory{}
48 | } else {
49 | factory = LightThemeFactory{}
50 | }
51 |
52 | // Create a button using the factory
53 | button = factory.CreateButton()
54 |
55 | // Use the button
56 | fmt.Println(button.Render())
57 | }
58 |
--------------------------------------------------------------------------------
/creational/builder/README.md:
--------------------------------------------------------------------------------
1 | # Builder
2 |
3 | The Builder Design Pattern is a creational pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation so that the same construction process can create different representations.
4 |
5 | When you are building a complex object that has multiple parts or configuration options, creating and configuring the object directly within client code or via a constructor can become unwieldy and hard to read. The Builder pattern addresses this issue by providing a way to build the complex object step by step, with each step clearly encapsulated by a method in the builder.
6 |
7 | ## Example
8 |
9 | The Builder pattern is most useful when dealing with a complex object that requires a significant or complex process to construct. It's often employed in contexts where objects are built from a variety of parts that need to be created and assembled. It's also particularly helpful when you might have multiple representations of an object, or when you want to encapsulate the creation logic separate from the main application.
10 |
11 | In this example, `RequestBuilder` is used to construct a complex `http.Request` object. Each Set method in the builder sets a different attribute of the request and returns the builder itself, allowing the methods to be chained. The `Build` method is finally used to construct the `http.Request` object. This approach can make the creation of complex request objects more manageable and readable.
12 |
--------------------------------------------------------------------------------
/creational/builder/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | "strings"
7 | )
8 |
9 | type RequestBuilder struct {
10 | Method string
11 | URL string
12 | Header http.Header
13 | Body string
14 | }
15 |
16 | func NewRequestBuilder() *RequestBuilder {
17 | return &RequestBuilder{
18 | Header: make(http.Header),
19 | }
20 | }
21 |
22 | func (b *RequestBuilder) SetMethod(method string) *RequestBuilder {
23 | b.Method = strings.ToUpper(method)
24 | return b
25 | }
26 |
27 | func (b *RequestBuilder) SetURL(url string) *RequestBuilder {
28 | b.URL = url
29 | return b
30 | }
31 |
32 | func (b *RequestBuilder) SetHeader(key, value string) *RequestBuilder {
33 | b.Header.Add(key, value)
34 | return b
35 | }
36 |
37 | func (b *RequestBuilder) SetBody(body string) *RequestBuilder {
38 | b.Body = body
39 | return b
40 | }
41 |
42 | func (b *RequestBuilder) Build() (*http.Request, error) {
43 | req, err := http.NewRequest(b.Method, b.URL, strings.NewReader(b.Body))
44 | if err != nil {
45 | return nil, err
46 | }
47 |
48 | req.Header = b.Header
49 |
50 | return req, nil
51 | }
52 |
53 | func main() {
54 | builder := NewRequestBuilder().
55 | SetMethod("POST").
56 | SetURL("http://example.com").
57 | SetHeader("Content-Type", "application/json").
58 | SetBody(`{"key": "value"}`)
59 |
60 | req, err := builder.Build()
61 | if err != nil {
62 | panic(err)
63 | }
64 |
65 | fmt.Printf("%+v\n", req) // This prints the request object
66 | }
67 |
--------------------------------------------------------------------------------
/creational/factory/README.md:
--------------------------------------------------------------------------------
1 | # Factory
2 |
3 | The Factory Method Design Pattern is a creational pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This pattern is used when a class cannot anticipate the class of objects it needs to create.
4 |
5 | The Factory pattern is often used in situations where a system should be independent of how its objects are created, composed, and represented. It provides a simple way of decoupling the concrete objects from the parts of the system that use them.
6 |
7 | A factory method in a class is a method that returns objects of a varying prototype or class from some method call, which is assumed to be "new". The factories are a great way to implement the concept of abstraction by encapsulating the responsibilities of creating and initializing complex objects.
8 |
9 | ## Example
10 |
11 | In this example, we have a `Logger` interface that different types of loggers (like `ConsoleLogger` and `FileLogger`) implement. The `LoggerFactory` can create different types of loggers depending on the argument passed to `CreateLogger`.
12 |
13 | ```go
14 | type Logger interface {
15 | Log(message string)
16 | }
17 |
18 | type ConsoleLogger struct{}
19 |
20 | func (cl *ConsoleLogger) Log(message string) {
21 | fmt.Println(message)
22 | }
23 |
24 | type FileLogger struct {
25 | file *os.File
26 | }
27 |
28 | func (fl *FileLogger) Log(message string) {
29 | fmt.Fprintln(fl.file, message)
30 | }
31 |
32 | type LoggerFactory struct{}
33 |
34 | func (lf *LoggerFactory) CreateLogger(loggerType string) (Logger, error) {
35 | switch loggerType {
36 | case "console":
37 | return &ConsoleLogger{}, nil
38 | case "file":
39 | file, err := os.Create("log.txt")
40 | if err != nil {
41 | return nil, err
42 | }
43 | return &FileLogger{file: file}, nil
44 | default:
45 | return nil, fmt.Errorf("unsupported logger type")
46 | }
47 | }
48 | ```
49 |
50 | This could be part of a larger logging library where you can choose between different types of loggers depending on your requirements. For example, you might use a `ConsoleLogger` in a development environment to print logs for debugging, but in a production environment, you might use a `FileLogger` or maybe a `DatabaseLogger` to store logs more permanently.
51 |
--------------------------------------------------------------------------------
/creational/factory/log.txt:
--------------------------------------------------------------------------------
1 | Hello from file logger!
2 |
--------------------------------------------------------------------------------
/creational/factory/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | )
7 |
8 | type Logger interface {
9 | Log(message string)
10 | }
11 |
12 | type ConsoleLogger struct{}
13 |
14 | func (cl *ConsoleLogger) Log(message string) {
15 | fmt.Println(message)
16 | }
17 |
18 | type FileLogger struct {
19 | file *os.File
20 | }
21 |
22 | func (fl *FileLogger) Log(message string) {
23 | fmt.Fprintln(fl.file, message)
24 | }
25 |
26 | type LoggerFactory struct{}
27 |
28 | func (lf *LoggerFactory) CreateLogger(loggerType string) (Logger, error) {
29 | switch loggerType {
30 | case "console":
31 | return &ConsoleLogger{}, nil
32 | case "file":
33 | file, err := os.Create("log.txt")
34 | if err != nil {
35 | return nil, err
36 | }
37 | return &FileLogger{file: file}, nil
38 | default:
39 | return nil, fmt.Errorf("unsupported logger type")
40 | }
41 | }
42 |
43 | func main() {
44 | loggerFactory := &LoggerFactory{}
45 |
46 | logger, err := loggerFactory.CreateLogger("console")
47 | if err != nil {
48 | panic(err)
49 | }
50 | logger.Log("Hello from console logger!")
51 |
52 | logger, err = loggerFactory.CreateLogger("file")
53 | if err != nil {
54 | panic(err)
55 | }
56 | logger.Log("Hello from file logger!")
57 | }
58 |
--------------------------------------------------------------------------------
/creational/prototype/README.md:
--------------------------------------------------------------------------------
1 | # Prototype
2 |
3 | The prototype design pattern involves creating objects based on a template of an existing object through cloning. It is especially useful when the construction of a new object is inefficient or complex.
4 |
5 | In the prototype pattern, an instance of actual object (which is created by expensive database operation) is cloned to create a new object. This pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs.
6 |
7 | This pattern involves implementing a prototype interface which tells to create a clone of the current object. It is used when creation of object directly is costly. So instead of creating a costly object, an existing object is copied.
8 |
9 | In Go, this can be implemented by using the `Clone` method in an interface that all the struct who want to use the Prototype pattern needs to implement. The `Clone` method will return an instance of itself.
10 |
11 | ## Example
12 |
13 | Let's imagine you're developing an application where you're dealing with different types of `Form` objects, each representing a form in a web application with many pre-filled fields. Each Form object is expensive to create (imagine it makes a network request or a database query to populate some of its fields). Therefore, instead of creating a new Form object each time a user visits a form, you might want to clone a pre-populated prototype.
14 |
15 | ```go
16 | // RegistrationForm is a concrete type implementing Form
17 | type RegistrationForm struct {
18 | Name string
19 | Email string
20 | }
21 |
22 | // Clone method for RegistrationForm
23 | func (r *RegistrationForm) Clone() Form {
24 | return &RegistrationForm{
25 | Name: r.Name,
26 | Email: r.Email,
27 | }
28 | }
29 | ```
30 |
31 | In this example, when a new `RegistrationForm` is needed, instead of creating a new one from scratch (which may be expensive due to required default data), we clone a pre-populated `RegistrationForm`. The `Clone` function allows each type of form to specify how it should be copied, providing a lot of flexibility. In the real world, the `Clone` method could handle deep copying and other complex copying logic.
32 |
33 | While it might seem unnecessary for a simple example like this, in a larger, more complex system, creating a new instance of an object can sometimes be a relatively expensive operation in terms of resources.
34 |
35 | Consider a case where the constructor of a class makes a call to a database, retrieves a large amount of data, and populates a complex object graph. In this case, creating a new instance is a time and resource-consuming operation.
36 |
37 | Now, suppose we often need to create objects that are identical or slightly different. In this case, it's much more efficient to clone the existing instance and modify it as needed, rather than creating a new one from scratch.
38 |
39 | In the Prototype design pattern, the `Clone` method isn't just copying the fields of an object. It could also be handling some more complex operations that are required to correctly copy an object, such as deep copying and managing references.
40 |
41 | Again, whether or not to use the Prototype pattern or simply clone/copy an object depends on the specific needs and constraints of your project. In many cases, especially for simple objects, a straightforward copy or a new object instantiation is preferable and leads to more readable code. However, in some scenarios where object creation is resource-intensive, the Prototype pattern can be a good approach.
42 |
--------------------------------------------------------------------------------
/creational/prototype/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Form - our prototype interface
6 | type Form interface {
7 | Clone() Form
8 | }
9 |
10 | // RegistrationForm is a concrete type implementing Form
11 | type RegistrationForm struct {
12 | Name string
13 | Email string
14 | }
15 |
16 | // Clone method for RegistrationForm
17 | func (r *RegistrationForm) Clone() Form {
18 | return &RegistrationForm{
19 | Name: r.Name,
20 | Email: r.Email,
21 | }
22 | }
23 |
24 | func main() {
25 | // create a prototype of the RegistrationForm
26 | prototype := &RegistrationForm{
27 | Name: "Default Name",
28 | Email: "default@example.com",
29 | }
30 |
31 | // use the prototype to clone a new form
32 | clonedForm := prototype.Clone()
33 |
34 | // type assertion to RegistrationForm
35 | regForm, ok := clonedForm.(*RegistrationForm)
36 | if !ok {
37 | fmt.Println("Type assertion to RegistrationForm failed")
38 | return
39 | }
40 |
41 | fmt.Printf("Name: %s, Email: %s\n", regForm.Name, regForm.Email)
42 | }
43 |
--------------------------------------------------------------------------------
/creational/singleton/README.md:
--------------------------------------------------------------------------------
1 | # Singleton
2 |
3 | The Singleton pattern is a design pattern that restricts the instantiation of a class to a single instance. This is useful when exactly one object is needed to coordinate actions across the system.
4 |
5 | The Singleton pattern is used for logging, driver objects, caching, thread pools, and database connections. It is a relatively simple pattern, but it comes with its own set of complications. The main issue is that it introduces global state into an application. For this reason, it's generally not considered a good practice to use singletons in a system that you want to be easy to test and maintain. However, it can be useful in certain scenarios where you need to coordinate logic in a globally accessible way.
6 |
7 | ## Example
8 |
9 | The singleton `WorkerPool` is the focus of this example. It's a structure containing a pool of workers, a pool of jobs and a `WaitGroup`.
10 |
11 | ```go
12 | type WorkerPool struct {
13 | workers []*Worker
14 | jobQueue chan Job
15 | workerPool chan chan Job
16 | wg sync.WaitGroup
17 | }
18 | ```
19 |
20 | Each `Worker` has a job channel to receive jobs and a quit channel for termination. When the worker is started, it continually listens on its job channel for incoming jobs and signals the `WaitGroup` when the job is done. When it receives a job, it prints a message. If it receives a signal on the quit channel, it stops.
21 |
22 | ```go
23 | type Worker struct {
24 | ID int
25 | WorkerPool chan chan Job
26 | JobChannel chan Job
27 | quit chan bool
28 | }
29 |
30 | func NewWorker(workerPool chan chan Job, id int) *Worker {
31 | return &Worker{
32 | ID: id,
33 | WorkerPool: workerPool,
34 | JobChannel: make(chan Job),
35 | quit: make(chan bool),
36 | }
37 | }
38 |
39 | func (w *Worker) Start(wg *sync.WaitGroup) {
40 | go func() {
41 | for {
42 | w.WorkerPool <- w.JobChannel
43 | select {
44 | case job := <-w.JobChannel:
45 | fmt.Printf("Worker %d received job %d\n", w.ID, job.ID)
46 | wg.Done()
47 | case <-w.quit:
48 | return
49 | }
50 | }
51 | }()
52 | }
53 |
54 | func (w *Worker) Stop() {
55 | go func() {
56 | w.quit <- true
57 | }()
58 | }
59 | ```
60 |
61 | `Job` is a simple structure with just an ID. It represents a task that needs to be done by a worker.
62 |
63 | ```go
64 | type Job struct {
65 | ID int
66 | }
67 | ```
68 |
69 | The singleton `WorkerPool` is initialized using `GetWorkerPool`, which ensures the singleton nature using `sync.Once`. Inside `GetWorkerPool`, a number of workers are started equal to `maxWorkers`. A dispatch function is also started that continually listens for incoming jobs on the jobs channel of the `WorkerPool`, and assigns each job to a worker. The `AddJob` method increases the `WaitGroup` counter and sends the job into the `jobQueue`. The `dispatch` method pulls jobs from `jobQueue` and sends them to available workers, ensuring that jobs are distributed to workers as they become available. The `Wait` method of the `WorkerPool` waits for all jobs to finish. In the main function, we call this method after all jobs have been added to ensure that the program doesn't exit until all jobs have been processed.
70 |
71 | ```go
72 | func GetWorkerPool(maxWorkers int) *WorkerPool {
73 | once.Do(func() {
74 | workers := make([]*Worker, maxWorkers)
75 | workerPool := make(chan chan Job, maxWorkers)
76 | jobQueue := make(chan Job, maxWorkers)
77 |
78 | pool := &WorkerPool{
79 | workers: workers,
80 | jobQueue: jobQueue,
81 | workerPool: workerPool,
82 | }
83 |
84 | for i := 0; i < maxWorkers; i++ {
85 | worker := NewWorker(pool.workerPool, i)
86 | worker.Start(&pool.wg)
87 | workers[i] = worker
88 | }
89 |
90 | go pool.dispatch()
91 |
92 | singleton = pool
93 | })
94 |
95 | return singleton
96 | }
97 |
98 | func (wp *WorkerPool) dispatch() {
99 | for job := range wp.jobQueue {
100 | workerJobQueue := <-wp.workerPool
101 | workerJobQueue <- job
102 | }
103 | }
104 |
105 | func (wp *WorkerPool) AddJob(job Job) {
106 | wp.wg.Add(1)
107 | wp.jobQueue <- job
108 | }
109 |
110 | func (wp *WorkerPool) Wait() {
111 | wp.wg.Wait()
112 | }
113 | ```
114 |
115 | This code will start 5 workers and process 20 jobs. Each job will be picked up by an available worker and processed concurrently. The main function will wait for all jobs to be processed before exiting.
116 |
117 | ```go
118 | func main() {
119 | wp := GetWorkerPool(5)
120 |
121 | for i := 1; i <= 20; i++ {
122 | job := Job{ID: i}
123 | wp.AddJob(job)
124 | }
125 |
126 | wp.Wait()
127 | }
128 | ```
129 |
--------------------------------------------------------------------------------
/creational/singleton/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | type Job struct {
9 | ID int
10 | }
11 |
12 | type Worker struct {
13 | ID int
14 | WorkerPool chan chan Job
15 | JobChannel chan Job
16 | quit chan bool
17 | }
18 |
19 | type WorkerPool struct {
20 | workers []*Worker
21 | jobQueue chan Job
22 | workerPool chan chan Job
23 | wg sync.WaitGroup
24 | }
25 |
26 | var once sync.Once
27 | var singleton *WorkerPool
28 |
29 | func NewWorker(workerPool chan chan Job, id int) *Worker {
30 | return &Worker{
31 | ID: id,
32 | WorkerPool: workerPool,
33 | JobChannel: make(chan Job),
34 | quit: make(chan bool),
35 | }
36 | }
37 |
38 | func (w *Worker) Start(wg *sync.WaitGroup) {
39 | go func() {
40 | for {
41 | w.WorkerPool <- w.JobChannel
42 | select {
43 | case job := <-w.JobChannel:
44 | fmt.Printf("Worker %d received job %d\n", w.ID, job.ID)
45 | wg.Done()
46 | case <-w.quit:
47 | return
48 | }
49 | }
50 | }()
51 | }
52 |
53 | func (w *Worker) Stop() {
54 | go func() {
55 | w.quit <- true
56 | }()
57 | }
58 |
59 | func GetWorkerPool(maxWorkers int) *WorkerPool {
60 | once.Do(func() {
61 | workers := make([]*Worker, maxWorkers)
62 | workerPool := make(chan chan Job, maxWorkers)
63 | jobQueue := make(chan Job, maxWorkers)
64 |
65 | pool := &WorkerPool{
66 | workers: workers,
67 | jobQueue: jobQueue,
68 | workerPool: workerPool,
69 | }
70 |
71 | for i := 0; i < maxWorkers; i++ {
72 | worker := NewWorker(pool.workerPool, i)
73 | worker.Start(&pool.wg)
74 | workers[i] = worker
75 | }
76 |
77 | go pool.dispatch()
78 |
79 | singleton = pool
80 | })
81 |
82 | return singleton
83 | }
84 |
85 | func (wp *WorkerPool) dispatch() {
86 | for job := range wp.jobQueue {
87 | workerJobQueue := <-wp.workerPool
88 | workerJobQueue <- job
89 | }
90 | }
91 |
92 | func (wp *WorkerPool) AddJob(job Job) {
93 | wp.wg.Add(1)
94 | wp.jobQueue <- job
95 | }
96 |
97 | func (wp *WorkerPool) Wait() {
98 | wp.wg.Wait()
99 | }
100 |
101 | func main() {
102 | wp := GetWorkerPool(5)
103 |
104 | for i := 1; i <= 20; i++ {
105 | job := Job{ID: i}
106 | wp.AddJob(job)
107 | }
108 |
109 | wp.Wait()
110 | }
111 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/araujo88/design-patterns-in-go/tree/main
2 |
3 | go 1.20
4 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/leo-aa88/design-patterns-in-go/b1ecfd29985e22835f643d46053069082e90edb4/go.sum
--------------------------------------------------------------------------------
/other/data_access_object/README.md:
--------------------------------------------------------------------------------
1 | # Data Access Object (DAO)
2 |
3 | A Data Access Object (DAO) is a pattern used in software design to separate the logic that retrieves data from a database from the business logic of the application. Essentially, it creates an abstraction over the data source, which can be a database or an API or anything else where data is retrieved. The DAO interacts with the data source and provides an interface that the rest of the application can use, without having to know any details about how the data is stored or retrieved.
4 |
5 | This pattern is widely used because it allows the underlying data source to be changed without affecting the rest of the application. This means that if you decide to change from one database system to another, you would only have to modify the DAO layer and not the entire application.
6 |
7 | ## Example
8 |
9 | Here's a simple example of a DAO pattern in Go, working with a fictional user database.
10 |
11 | First, let's define the User struct and the DAO interface:
12 |
13 | ```go
14 | type User struct {
15 | ID int
16 | FirstName string
17 | LastName string
18 | }
19 |
20 | type UserDAO interface {
21 | GetUser(id int) (*User, error)
22 | GetAllUsers() ([]*User, error)
23 | SaveUser(user *User) error
24 | DeleteUser(id int) error
25 | }
26 | ```
27 |
28 | Now let's create a concrete implementation of this DAO interface. For simplicity, I'll use a mock in-memory database:
29 |
30 | ```go
31 | type UserDAOImpl struct {
32 | users map[int]*User
33 | }
34 |
35 | func (dao *UserDAOImpl) GetUser(id int) (*User, error) {
36 | user, exists := dao.users[id]
37 | if !exists {
38 | return nil, fmt.Errorf("User not found")
39 | }
40 | return user, nil
41 | }
42 |
43 | func (dao *UserDAOImpl) GetAllUsers() ([]*User, error) {
44 | userList := make([]*User, 0, len(dao.users))
45 | for _, user := range dao.users {
46 | userList = append(userList, user)
47 | }
48 | return userList, nil
49 | }
50 |
51 | func (dao *UserDAOImpl) SaveUser(user *User) error {
52 | dao.users[user.ID] = user
53 | return nil
54 | }
55 |
56 | func (dao *UserDAOImpl) DeleteUser(id int) error {
57 | _, exists := dao.users[id]
58 | if !exists {
59 | return fmt.Errorf("User not found")
60 | }
61 | delete(dao.users, id)
62 | return nil
63 | }
64 | ```
65 |
66 | Create a Service that Depends on the `UserDAO` Interface:
67 |
68 | ```go
69 | type UserService struct {
70 | userDao UserDAO
71 | }
72 |
73 | func NewUserService(dao UserDAO) *UserService {
74 | return &UserService{userDao: dao}
75 | }
76 |
77 | func (s *UserService) GetUserDetails(id int) (*User, error) {
78 | return s.userDao.GetUser(id)
79 | }
80 | ```
81 |
82 | Use the Service in the Main Function:
83 |
84 | ```go
85 | func main() {
86 | userDao := &UserDAOImpl{
87 | users: make(map[int]*User),
88 | }
89 | userService := NewUserService(userDao)
90 |
91 | user := &User{
92 | ID: 1,
93 | FirstName: "Giga",
94 | LastName: "Chad",
95 | }
96 | userDao.SaveUser(user)
97 |
98 | retrievedUser, err := userService.GetUserDetails(1)
99 | if err != nil {
100 | log.Fatal(err)
101 | }
102 | fmt.Println("Retrieved User:", retrievedUser.FirstName, retrievedUser.LastName)
103 | }
104 | ```
105 |
106 | Here, the `UserService` depends on the `UserDAO` interface, not the concrete `UserDAOImpl`. This way, if you decide to change how users are stored (e.g., switching from an in-memory database to a SQL database), you can create a new implementation of the `UserDAO` interface without changing the `UserService`.
107 |
108 | This example illustrates the DAO pattern's decoupling concept. By relying on interfaces, different parts of the application can interact without knowing the underlying implementation details, leading to more maintainable and flexible code.
109 |
--------------------------------------------------------------------------------
/other/data_access_object/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | )
7 |
8 | type User struct {
9 | ID int
10 | FirstName string
11 | LastName string
12 | }
13 |
14 | type UserDAO interface {
15 | GetUser(id int) (*User, error)
16 | GetAllUsers() ([]*User, error)
17 | SaveUser(user *User) error
18 | DeleteUser(id int) error
19 | }
20 |
21 | type UserDAOImpl struct {
22 | users map[int]*User
23 | }
24 |
25 | func (dao *UserDAOImpl) GetUser(id int) (*User, error) {
26 | user, exists := dao.users[id]
27 | if !exists {
28 | return nil, fmt.Errorf("User not found")
29 | }
30 | return user, nil
31 | }
32 |
33 | func (dao *UserDAOImpl) GetAllUsers() ([]*User, error) {
34 | userList := make([]*User, 0, len(dao.users))
35 | for _, user := range dao.users {
36 | userList = append(userList, user)
37 | }
38 | return userList, nil
39 | }
40 |
41 | func (dao *UserDAOImpl) SaveUser(user *User) error {
42 | dao.users[user.ID] = user
43 | return nil
44 | }
45 |
46 | func (dao *UserDAOImpl) DeleteUser(id int) error {
47 | _, exists := dao.users[id]
48 | if !exists {
49 | return fmt.Errorf("User not found")
50 | }
51 | delete(dao.users, id)
52 | return nil
53 | }
54 |
55 | type UserService struct {
56 | userDao UserDAO
57 | }
58 |
59 | func NewUserService(dao UserDAO) *UserService {
60 | return &UserService{userDao: dao}
61 | }
62 |
63 | func (s *UserService) GetUserDetails(id int) (*User, error) {
64 | return s.userDao.GetUser(id)
65 | }
66 |
67 | func main() {
68 | userDao := &UserDAOImpl{
69 | users: make(map[int]*User),
70 | }
71 | userService := NewUserService(userDao)
72 |
73 | user := &User{
74 | ID: 1,
75 | FirstName: "Giga",
76 | LastName: "Chad",
77 | }
78 | userDao.SaveUser(user)
79 |
80 | retrievedUser, err := userService.GetUserDetails(1)
81 | if err != nil {
82 | log.Fatal(err)
83 | }
84 | fmt.Println("Retrieved User:", retrievedUser.FirstName, retrievedUser.LastName)
85 | }
86 |
--------------------------------------------------------------------------------
/other/dependency_injection/README.md:
--------------------------------------------------------------------------------
1 | # Dependency Injection
2 |
3 | Dependency Injection is a design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time. This pattern is particularly useful for decoupling components and improving code maintainability and testability.
4 |
5 | In simple terms, Dependency Injection means that if a class needs access to an external resource (like a database, or another class), instead of creating it inside the class, you "inject" it into the class from the outside.
6 |
7 | ### Participants
8 |
9 | - **Client**: The class that depends on the service.
10 | - **Service**: The service that the client needs.
11 | - **Injector**: This class injects the service into the client.
12 |
13 | ## Example
14 |
15 | Below is a simplified example in Go that demonstrates Dependency Injection. We have an `Author` struct that uses an interface `Writer` to write something. We then have two implementations of `Writer`: `ConsoleWriter` and `FileWriter`. Through dependency injection, we can easily switch between writing to the console and writing to a file without modifying the `Author` struct.
16 |
17 | ```go
18 | // Writer interface, the 'Service' in our example
19 | type Writer interface {
20 | Write([]byte) error
21 | }
22 |
23 | // ConsoleWriter writes to the console, one of the 'ConcreteService'
24 | type ConsoleWriter struct{}
25 |
26 | func (cw *ConsoleWriter) Write(data []byte) error {
27 | _, err := fmt.Println(string(data))
28 | return err
29 | }
30 |
31 | // FileWriter writes to a file, another 'ConcreteService'
32 | type FileWriter struct {
33 | filename string
34 | }
35 |
36 | func (fw *FileWriter) Write(data []byte) error {
37 | return ioutil.WriteFile(fw.filename, data, 0644)
38 | }
39 |
40 | // Author is the 'Client'
41 | type Author struct {
42 | writer Writer // Author depends on a Writer to do the writing
43 | }
44 |
45 | // NewAuthor creates a new author with a writer
46 | func NewAuthor(writer Writer) *Author {
47 | return &Author{writer}
48 | }
49 |
50 | // WriteArticle uses the injected writer to write an article
51 | func (a *Author) WriteArticle(article string) error {
52 | return a.writer.Write([]byte(article))
53 | }
54 | ```
55 |
56 | In this example:
57 |
58 | - `Writer` is the service interface that defines a `Write` method.
59 | - `ConsoleWriter` and `FileWriter` are concrete implementations of the `Writer` interface.
60 | - `Author` is the client that depends on a service implementing the `Writer` interface.
61 |
62 | We inject the `Writer` dependency into `Author` via the `NewAuthor` function. This decouples `Author` from the concrete implementations (`ConsoleWriter` and `FileWriter`) and makes the system easier to extend, test, and maintain.
63 |
64 | With Dependency Injection, you can easily swap out the `Writer` implementation without modifying the `Author` code, making the system more modular and easier to test.
65 |
--------------------------------------------------------------------------------
/other/dependency_injection/article.txt:
--------------------------------------------------------------------------------
1 | Article to file
--------------------------------------------------------------------------------
/other/dependency_injection/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io/ioutil"
6 | )
7 |
8 | // Writer interface, the 'Service' in our example
9 | type Writer interface {
10 | Write([]byte) error
11 | }
12 |
13 | // ConsoleWriter writes to the console, one of the 'ConcreteService'
14 | type ConsoleWriter struct{}
15 |
16 | func (cw *ConsoleWriter) Write(data []byte) error {
17 | _, err := fmt.Println(string(data))
18 | return err
19 | }
20 |
21 | // FileWriter writes to a file, another 'ConcreteService'
22 | type FileWriter struct {
23 | filename string
24 | }
25 |
26 | func (fw *FileWriter) Write(data []byte) error {
27 | return ioutil.WriteFile(fw.filename, data, 0644)
28 | }
29 |
30 | // Author is the 'Client'
31 | type Author struct {
32 | writer Writer // Author depends on a Writer to do the writing
33 | }
34 |
35 | // NewAuthor creates a new author with a writer
36 | func NewAuthor(writer Writer) *Author {
37 | return &Author{writer}
38 | }
39 |
40 | // WriteArticle uses the injected writer to write an article
41 | func (a *Author) WriteArticle(article string) error {
42 | return a.writer.Write([]byte(article))
43 | }
44 |
45 | func main() {
46 | // Inject ConsoleWriter dependency into Author
47 | author1 := NewAuthor(&ConsoleWriter{})
48 | _ = author1.WriteArticle("Article to console")
49 |
50 | // Inject FileWriter dependency into Author
51 | author2 := NewAuthor(&FileWriter{filename: "article.txt"})
52 | _ = author2.WriteArticle("Article to file")
53 | }
54 |
--------------------------------------------------------------------------------
/other/repository/README.md:
--------------------------------------------------------------------------------
1 | # Repository
2 |
3 | The Repository pattern is a structural pattern used to separate the logic that retrieves data from a database (or any other source) from the business logic of the application. The Repository mediates between the application’s business logic and data source, acting like an in-memory collection of domain objects. Clients interact with a Repository as they would interact with a simple collection of objects, using methods like `Add`, `Remove`, and `Find`.
4 |
5 | ### Benefits
6 |
7 | 1. **Separation of Concerns**: It separates the logic of data access from the business logic.
8 | 2. **Testability**: Because the data logic is decoupled, it's easier to write unit tests for the business logic.
9 | 3. **Maintainability**: The code is more maintainable and readable, as each part follows the Single Responsibility Principle.
10 |
11 | ## Example
12 |
13 | Below is an example in Go that uses the Repository pattern. It demonstrates a simple CRUD operation for managing books in a library.
14 |
15 | ```go
16 | // Book represents a book in a library
17 | type Book struct {
18 | ID string
19 | Title string
20 | Author string
21 | }
22 |
23 | // BookRepository interface for persisting books
24 | type BookRepository interface {
25 | Add(Book) error
26 | Remove(string) error
27 | FindById(string) (*Book, error)
28 | FindAll() ([]*Book, error)
29 | }
30 |
31 | // InMemoryBookRepository is an in-memory implementation of BookRepository
32 | type InMemoryBookRepository struct {
33 | books map[string]*Book
34 | }
35 |
36 | // NewInMemoryBookRepository initializes a new InMemoryBookRepository
37 | func NewInMemoryBookRepository() *InMemoryBookRepository {
38 | return &InMemoryBookRepository{
39 | books: make(map[string]*Book),
40 | }
41 | }
42 |
43 | func (r *InMemoryBookRepository) Add(b Book) error {
44 | r.books[b.ID] = &b
45 | return nil
46 | }
47 |
48 | func (r *InMemoryBookRepository) Remove(id string) error {
49 | delete(r.books, id)
50 | return nil
51 | }
52 |
53 | func (r *InMemoryBookRepository) FindById(id string) (*Book, error) {
54 | if book, ok := r.books[id]; ok {
55 | return book, nil
56 | }
57 | return nil, fmt.Errorf("Book not found")
58 | }
59 |
60 | func (r *InMemoryBookRepository) FindAll() ([]*Book, error) {
61 | var books []*Book
62 | for _, book := range r.books {
63 | books = append(books, book)
64 | }
65 | return books, nil
66 | }
67 | ```
68 |
69 | In this example:
70 |
71 | - `Book` is the domain object.
72 | - `BookRepository` is the interface that defines methods for accessing `Book` objects.
73 | - `InMemoryBookRepository` is the concrete implementation of the `BookRepository`, which stores `Book` objects in an in-memory map.
74 |
75 | This separation makes it easier to change the data source or implement additional features like caching. It also simplifies testing, as you can easily mock the `BookRepository` when testing components that rely on it.
76 |
77 | ## Differences between DAO and Repository patterns
78 |
79 | Both the Repository and Data Access Object (DAO) patterns aim to separate the concerns of data access from the rest of the application, but they differ in scope, abstraction level, and how they are used in the context of an application. Here are some key differences:
80 |
81 | ### Abstraction Level
82 |
83 | - **Repository Pattern**: Provides a higher level of abstraction by dealing with domain objects and collections of domain objects. A repository typically works with aggregates in terms of Domain-Driven Design (DDD) and operates in the context of the business domain, effectively decoupling the domain model from the data model.
84 |
85 | - **DAO Pattern**: Focuses on providing a low-level abstraction over the database interactions. It directly deals with data source APIs and is generally closer to the database, often reflecting the database's structure, tables, or stored procedures.
86 |
87 | ### Operations
88 |
89 | - **Repository Pattern**: Methods in repositories often have a business-centric language. For example, you may have methods like `FindActiveUsers` or `GetOverdueAccounts`, which represent specific business rules.
90 |
91 | - **DAO Pattern**: Methods in a DAO are usually CRUD-oriented (Create, Read, Update, Delete) and closely represent the operations you can perform on the table itself. You might find methods like `Insert`, `Update`, `Delete`, `FindById`, etc.
92 |
93 | ### Aggregation
94 |
95 | - **Repository Pattern**: Typically deals with aggregates, which are cluster of domain objects that can be treated as a single unit, and often returns fully instantiated aggregates that are ready for use by the client code.
96 |
97 | - **DAO Pattern**: Generally works with individual records in tables and doesn't concern itself with object graphs or aggregates.
98 |
99 | ### Usage Context
100 |
101 | - **Repository Pattern**: Commonly used in Domain-Driven Design and places an emphasis on business rules and the domain. It's often used in more complex applications where business logic needs to be decoupled from data access logic.
102 |
103 | - **DAO Pattern**: More general-purpose and can be used effectively in simpler, CRUD-based applications or any application that doesn't place much emphasis on domain-driven design.
104 |
105 | ### Interface Location
106 |
107 | - **Repository Pattern**: Usually defined in the domain layer and is meant to be an abstraction of a collection of domain objects.
108 |
109 | - **DAO Pattern**: Defined in the data access layer and serves as an abstraction for database operations.
110 |
111 | ### Testability
112 |
113 | - Both patterns aim to improve testability by separating data access concerns from business logic, but the Repository pattern often goes a step further by working well with domain-centric unit tests, given its higher level of abstraction.
114 |
115 | While both patterns aim to achieve similar separation of concerns, the way they go about it and their typical usages are different. Sometimes, you might even use both in the same application: DAOs can be used to handle the low-level data access details, while repositories use DAOs internally to implement the higher-level, domain-specific data access interfaces.
116 |
--------------------------------------------------------------------------------
/other/repository/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Book represents a book in a library
6 | type Book struct {
7 | ID string
8 | Title string
9 | Author string
10 | }
11 |
12 | // BookRepository interface for persisting books
13 | type BookRepository interface {
14 | Add(Book) error
15 | Remove(string) error
16 | FindById(string) (*Book, error)
17 | FindAll() ([]*Book, error)
18 | }
19 |
20 | // InMemoryBookRepository is an in-memory implementation of BookRepository
21 | type InMemoryBookRepository struct {
22 | books map[string]*Book
23 | }
24 |
25 | // NewInMemoryBookRepository initializes a new InMemoryBookRepository
26 | func NewInMemoryBookRepository() *InMemoryBookRepository {
27 | return &InMemoryBookRepository{
28 | books: make(map[string]*Book),
29 | }
30 | }
31 |
32 | func (r *InMemoryBookRepository) Add(b Book) error {
33 | r.books[b.ID] = &b
34 | return nil
35 | }
36 |
37 | func (r *InMemoryBookRepository) Remove(id string) error {
38 | delete(r.books, id)
39 | return nil
40 | }
41 |
42 | func (r *InMemoryBookRepository) FindById(id string) (*Book, error) {
43 | if book, ok := r.books[id]; ok {
44 | return book, nil
45 | }
46 | return nil, fmt.Errorf("Book not found")
47 | }
48 |
49 | func (r *InMemoryBookRepository) FindAll() ([]*Book, error) {
50 | var books []*Book
51 | for _, book := range r.books {
52 | books = append(books, book)
53 | }
54 | return books, nil
55 | }
56 |
57 | func main() {
58 | repo := NewInMemoryBookRepository()
59 |
60 | // Add books
61 | repo.Add(Book{ID: "1", Title: "1984", Author: "George Orwell"})
62 | repo.Add(Book{ID: "2", Title: "Brave New World", Author: "Aldous Huxley"})
63 |
64 | // Find a book by ID
65 | book, err := repo.FindById("1")
66 | if err != nil {
67 | fmt.Println("Error:", err)
68 | } else {
69 | fmt.Println("Found book:", *book)
70 | }
71 |
72 | // Find all books
73 | allBooks, err := repo.FindAll()
74 | if err != nil {
75 | fmt.Println("Error:", err)
76 | } else {
77 | for _, book := range allBooks {
78 | fmt.Println(*book)
79 | }
80 | }
81 |
82 | // Remove a book
83 | err = repo.Remove("1")
84 | if err != nil {
85 | fmt.Println("Error:", err)
86 | }
87 |
88 | // Try to find the removed book
89 | book, err = repo.FindById("1")
90 | if err != nil {
91 | fmt.Println("Error:", err)
92 | } else {
93 | fmt.Println("Found book:", *book)
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/other/service_locator/README.md:
--------------------------------------------------------------------------------
1 | # Service locator
2 |
3 | The Service Locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the "service locator", which on request returns the information necessary to perform a certain task.
4 |
5 | Here is a brief summary of the pattern:
6 |
7 | - The service locator is a known point for obtaining services.
8 | - The service locator may 'know' how to get hold of the service itself, or it might contain a record of suitable services (i.e., a registry).
9 | - An application will ask the service locator for the service by passing a string identifier or a key.
10 | - The locator will return the service to the application so that the application can use it.
11 |
12 | This pattern introduces an abstraction layer between the service consumer and the concrete classes providing those services. This abstraction layer provides a way to manage dependencies and to do runtime binding of the required service.
13 |
14 | ## Example
15 |
16 | The Service Locator pattern is commonly used in situations where program configuration dictates what services to use. This pattern is particularly popular in microservice architectures and large enterprise systems, where services might be spread across different servers or even geographic regions.
17 |
18 | The following example uses a service locator to switch between different databases (PostgreSQL and MySQL). We'll create a generic `DatabaseService` interface, and two structs implementing it, one for each database.
19 |
20 | ```go
21 | // Define our Service Interface
22 | type DatabaseService interface {
23 | GetName() string
24 | Connect() string
25 | }
26 |
27 | type PostgreSQL struct{}
28 |
29 | func (p *PostgreSQL) GetName() string {
30 | return "PostgreSQL"
31 | }
32 |
33 | func (p *PostgreSQL) Connect() string {
34 | return "Connected to PostgreSQL"
35 | }
36 |
37 | type MySQL struct{}
38 |
39 | func (m *MySQL) GetName() string {
40 | return "MySQL"
41 | }
42 |
43 | func (m *MySQL) Connect() string {
44 | return "Connected to MySQL"
45 | }
46 |
47 | // Service Locator
48 | type DatabaseServiceLocator struct {
49 | services map[string]DatabaseService
50 | }
51 |
52 | func (sl *DatabaseServiceLocator) GetService(serviceName string) (DatabaseService, error) {
53 | service, ok := sl.services[serviceName]
54 | if ok {
55 | return service, nil
56 | }
57 | return nil, fmt.Errorf("Service Not Found")
58 | }
59 |
60 | func (sl *DatabaseServiceLocator) RegisterService(service DatabaseService) {
61 | sl.services[service.GetName()] = service
62 | }
63 | ```
64 |
65 | In this example, we have defined a common interface (`DatabaseService`) for our databases and implemented it for PostgreSQL and MySQL. The `DatabaseServiceLocator` is our service locator which maintains a registry of services. We can fetch a specific database service by its name, and then call Connect() to simulate establishing a connection to the database.
66 |
67 | We use the service locator in our main() function to fetch and connect to our databases. The type of database we're connecting to could be configured based on external factors, like application configuration or environment variables, making the system highly flexible.
68 |
--------------------------------------------------------------------------------
/other/service_locator/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | )
7 |
8 | // Define our Service Interface
9 | type DatabaseService interface {
10 | GetName() string
11 | Connect() string
12 | }
13 |
14 | type PostgreSQL struct{}
15 |
16 | func (p *PostgreSQL) GetName() string {
17 | return "PostgreSQL"
18 | }
19 |
20 | func (p *PostgreSQL) Connect() string {
21 | return "Connected to PostgreSQL"
22 | }
23 |
24 | type MySQL struct{}
25 |
26 | func (m *MySQL) GetName() string {
27 | return "MySQL"
28 | }
29 |
30 | func (m *MySQL) Connect() string {
31 | return "Connected to MySQL"
32 | }
33 |
34 | // Service Locator
35 | type DatabaseServiceLocator struct {
36 | services map[string]DatabaseService
37 | }
38 |
39 | func (sl *DatabaseServiceLocator) GetService(serviceName string) (DatabaseService, error) {
40 | service, ok := sl.services[serviceName]
41 | if ok {
42 | return service, nil
43 | }
44 | return nil, fmt.Errorf("Service Not Found")
45 | }
46 |
47 | func (sl *DatabaseServiceLocator) RegisterService(service DatabaseService) {
48 | sl.services[service.GetName()] = service
49 | }
50 |
51 | func main() {
52 | locator := &DatabaseServiceLocator{
53 | services: make(map[string]DatabaseService),
54 | }
55 |
56 | postgres := &PostgreSQL{}
57 | locator.RegisterService(postgres)
58 |
59 | mysql := &MySQL{}
60 | locator.RegisterService(mysql)
61 |
62 | // Fetch PostgreSQL service and connect
63 | service, err := locator.GetService("PostgreSQL")
64 | if err != nil {
65 | log.Fatal(err)
66 | }
67 | fmt.Println(service.Connect())
68 |
69 | // Fetch MySQL service and connect
70 | service, err = locator.GetService("MySQL")
71 | if err != nil {
72 | log.Fatal(err)
73 | }
74 | fmt.Println(service.Connect())
75 | }
76 |
--------------------------------------------------------------------------------
/structural/adapter/README.md:
--------------------------------------------------------------------------------
1 | # Adapter
2 |
3 | The Adapter Design Pattern is a structural design pattern that allows two incompatible interfaces to work together. This incompatibility could be because of differences in method names, argument types, or other differences in the interfaces.
4 |
5 | The Adapter acts as a wrapper between two objects. It catches calls for one object and transforms them to format and interface recognizable by the second object.
6 |
7 | Here's an example: Suppose you have a legacy system that returns data in an older format (like XML), and you have a new system that expects the data to be in a different format (like JSON). Instead of rewriting the legacy system, you could use an Adapter. This Adapter could take the XML data, convert it to JSON, and then provide the data to the new system.
8 |
9 | In a real-world scenario, an adapter is like having a USB-C to USB-A converter. You have a device that only supports USB-C as an input but you have a USB-A connector cable. So you use a converter/adapter to solve the incompatibility.
10 |
11 | The Adapter Design Pattern is all about creating an intermediary abstraction that translates, or adapts, the old component to the new system. An adapter wraps the legacy system with a new interface so that the legacy system can be used by the new system through the new interface. This way, the new system only interacts with the Adapter but the legacy system doesn't need to be modified.
12 |
13 | ## Example
14 |
15 | Imagine we have a legacy system that logs messages in a certain way and a new system that has a different interface for logging.
16 |
17 | The legacy system has a `LegacyLogger` with a `LogMessage` method:
18 |
19 | ```go
20 | type LegacyLogger struct {}
21 |
22 | func (l *LegacyLogger) LogMessage(message string) {
23 | fmt.Println("Legacy logger: " + message)
24 | }
25 | ```
26 |
27 | The new system uses an interface called `NewLogger` with a `Log` method:
28 |
29 | ```go
30 | type NewLogger interface {
31 | Log(message string)
32 | }
33 |
34 | type NewSystemLogger struct {}
35 |
36 | func (l *NewSystemLogger) Log(message string) {
37 | fmt.Println("New system logger: " + message)
38 | }
39 | ```
40 |
41 | You want the new system to be able to use the `LegacyLogger` without changing its code. You can create an adapter that implements the `NewLogger` interface, but uses the `LegacyLogger` internally:
42 |
43 | ```go
44 | type LoggerAdapter struct {
45 | legacyLogger *LegacyLogger
46 | }
47 |
48 | func (a *LoggerAdapter) Log(message string) {
49 | // Adapting the interface here:
50 | a.legacyLogger.LogMessage(message)
51 | }
52 | ```
53 |
54 | Now, you can use `LegacyLogger` in the new system:
55 |
56 | ```go
57 | func logMessage(message string, logger NewLogger) {
58 | logger.Log(message)
59 | }
60 |
61 | func main() {
62 | legacyLogger := &LegacyLogger{}
63 | loggerAdapter := &LoggerAdapter{legacyLogger: legacyLogger}
64 |
65 | logMessage("Hello, world!", loggerAdapter)
66 | }
67 | ```
68 |
69 | In this example, `LoggerAdapter` is the adapter. It wraps `LegacyLogger` (the adaptee) and makes it compatible with `NewLogger` (the target interface). The `Log` method in `LoggerAdapter` adapts the interface of `LegacyLogger` to the `NewLogger` interface. The client code (the `logMessage` function) works with the `NewLogger` interface, so it can now use `LegacyLogger` through the `LoggerAdapter`. This is the essence of the Adapter Pattern.
70 |
--------------------------------------------------------------------------------
/structural/adapter/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type LegacyLogger struct{}
6 |
7 | func (l *LegacyLogger) LogMessage(message string) {
8 | fmt.Println("Legacy logger: " + message)
9 | }
10 |
11 | type NewLogger interface {
12 | Log(message string)
13 | }
14 |
15 | type NewSystemLogger struct{}
16 |
17 | func (l *NewSystemLogger) Log(message string) {
18 | fmt.Println("New system logger: " + message)
19 | }
20 |
21 | type LoggerAdapter struct {
22 | legacyLogger *LegacyLogger
23 | }
24 |
25 | func (a *LoggerAdapter) Log(message string) {
26 | // Adapting the interface here:
27 | a.legacyLogger.LogMessage(message)
28 | }
29 |
30 | func logMessage(message string, logger NewLogger) {
31 | logger.Log(message)
32 | }
33 |
34 | func main() {
35 | legacyLogger := &LegacyLogger{}
36 | loggerAdapter := &LoggerAdapter{legacyLogger: legacyLogger}
37 | newLogger := &NewSystemLogger{}
38 |
39 | logMessage("Hello, world!", loggerAdapter)
40 | logMessage("Hello, world!", newLogger)
41 | }
42 |
--------------------------------------------------------------------------------
/structural/bridge/README.md:
--------------------------------------------------------------------------------
1 | # Bridge
2 |
3 | The Bridge Design Pattern is a structural design pattern that aims to decouple an abstraction from its implementation so that the two can vary independently. This is especially useful for providing platform independence and can also enhance extensibility.
4 |
5 | In other words, Bridge Pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.
6 |
7 | ## Example
8 |
9 | For example, consider different types of database drivers. We can have an interface called `DatabaseDriver` that has methods like `Connect()`, `ExecuteQuery()`, etc. Now, the actual implementations like `MySQLDriver`, `PostgresDriver`, `SQLiteDriver` will implement this `DatabaseDriver` interface and provide the actual implementation of these methods. So the abstraction layer (which could be an application using the database) will just call these methods and is not worried about what database system it is connecting to. This abstraction of implementation is the essence of the bridge pattern.
10 |
11 | ```go
12 | type IDatabase interface {
13 | Connect() string
14 | }
15 |
16 | type MySQL struct {
17 | }
18 |
19 | func (m MySQL) Connect() string {
20 | return "Connected to MySQL Database"
21 | }
22 |
23 | type Postgres struct {
24 | }
25 |
26 | func (p Postgres) Connect() string {
27 | return "Connected to Postgres Database"
28 | }
29 |
30 | type Application struct {
31 | database IDatabase
32 | }
33 |
34 | func (a *Application) SetDatabase(database IDatabase) {
35 | a.database = database
36 | }
37 |
38 | func (a *Application) Start() {
39 | fmt.Println(a.database.Connect())
40 | }
41 |
42 | ```
43 |
44 | In this example, we define an interface `IDatabase` that each of our specific database types (`MySQL`, `Postgres`) implements. This interface includes a method `Connect()`, which would be different for each database type. The `Application` struct then has a `SetDatabase()` method that accepts anything that fulfills the `IDatabase` interface.
45 |
46 | We then have a method `Start()` that prints the `Connect()` message. In a real-world application, it would contain the logic that is common to all databases. It could be interacting with the database, creating tables, performing CRUD operations, etc.
47 |
48 | By using the bridge pattern in this way, we're able to decouple the abstraction (our application's interaction with a database) from the implementation (the specific calls needed to interact with a MySQL or a PostgreSQL database).
49 |
--------------------------------------------------------------------------------
/structural/bridge/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type IDatabase interface {
6 | Connect() string
7 | }
8 |
9 | type MySQL struct {
10 | }
11 |
12 | func (m MySQL) Connect() string {
13 | return "Connected to MySQL Database"
14 | }
15 |
16 | type Postgres struct {
17 | }
18 |
19 | func (p Postgres) Connect() string {
20 | return "Connected to Postgres Database"
21 | }
22 |
23 | type Application struct {
24 | database IDatabase
25 | }
26 |
27 | func (a *Application) SetDatabase(database IDatabase) {
28 | a.database = database
29 | }
30 |
31 | func (a *Application) Start() {
32 | fmt.Println(a.database.Connect())
33 | }
34 |
35 | func main() {
36 | mysql := &MySQL{}
37 | postgres := &Postgres{}
38 |
39 | app := &Application{}
40 | app.SetDatabase(mysql)
41 | app.Start()
42 |
43 | app.SetDatabase(postgres)
44 | app.Start()
45 | }
46 |
--------------------------------------------------------------------------------
/structural/composite/README.md:
--------------------------------------------------------------------------------
1 | # Composite
2 |
3 | The Composite Design Pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. The Composite pattern lets clients treat individual objects and compositions of objects uniformly.
4 |
5 | This pattern is used when we need to treat a group of objects in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
6 |
7 | The composite pattern includes the following components:
8 |
9 | - Component: It is an interface for objects in the composition. It has methods to manage the child components. It can be an abstract class which contains default implementations. If there is no specific default implementations to put in the abstract class, it can also be an interface.
10 |
11 | - Leaf: It represents leaf objects in the composition. It has no children.
12 |
13 | - Composite: It stores the child components and implements the child related operations in the component interface.
14 |
15 | - Client: It manipulates objects in the composition through the component interface.
16 |
17 | A real-world example could be an organization hierarchy. Every employee of an organization is an object. The organization consists of departments and each department also has a list of employees. Here, each department can be seen as a composite object as it can be further divided into sub-departments. This way, the organization is the composition of employees and departments. This can be efficiently represented using the composite design pattern.
18 |
19 | ## Example
20 |
21 | Let's consider a file system as an example. In a file system, a directory can contain files or other directories. Here, both files and directories share similar operations such as calculating the size, searching for an item, etc.
22 |
23 | In this example, the Component can be an interface named `FileSystemNode`, the Leaf can be a `File` and the Composite can be a `Directory`. The `Directory` can contain both `File` and `Directory`.
24 |
25 | ```go
26 | // FileSystemNode : a component which can be a file or a directory
27 | type FileSystemNode interface {
28 | GetSize() int
29 | }
30 |
31 | // File : a leaf node in the file system
32 | type File struct {
33 | size int
34 | }
35 |
36 | // GetSize : returns size of the file
37 | func (f *File) GetSize() int {
38 | return f.size
39 | }
40 |
41 | // Directory : a composite node in the file system
42 | type Directory struct {
43 | children []FileSystemNode
44 | }
45 |
46 | // GetSize : returns total size of the directory (including all children)
47 | func (d *Directory) GetSize() int {
48 | size := 0
49 | for _, child := range d.children {
50 | size += child.GetSize()
51 | }
52 | return size
53 | }
54 |
55 | // AddChild : adds a new child node to the directory
56 | func (d *Directory) AddChild(child FileSystemNode) {
57 | d.children = append(d.children, child)
58 | }
59 | ```
60 |
61 | In this example, the client (`main` function) treats all files and directories uniformly by using the `FileSystemNode` interface. The client doesn't need to be aware of the concrete object it's dealing with. This is the primary benefit of the Composite Design Pattern.
62 |
--------------------------------------------------------------------------------
/structural/composite/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // FileSystemNode : a component which can be a file or a directory
6 | type FileSystemNode interface {
7 | GetSize() int
8 | }
9 |
10 | // File : a leaf node in the file system
11 | type File struct {
12 | size int
13 | }
14 |
15 | // GetSize : returns size of the file
16 | func (f *File) GetSize() int {
17 | return f.size
18 | }
19 |
20 | // Directory : a composite node in the file system
21 | type Directory struct {
22 | children []FileSystemNode
23 | }
24 |
25 | // GetSize : returns total size of the directory (including all children)
26 | func (d *Directory) GetSize() int {
27 | size := 0
28 | for _, child := range d.children {
29 | size += child.GetSize()
30 | }
31 | return size
32 | }
33 |
34 | // AddChild : adds a new child node to the directory
35 | func (d *Directory) AddChild(child FileSystemNode) {
36 | d.children = append(d.children, child)
37 | }
38 |
39 | func main() {
40 | file1 := &File{size: 200}
41 | file2 := &File{size: 300}
42 | dir := Directory{}
43 | dir.AddChild(file1)
44 | dir.AddChild(file2)
45 |
46 | fmt.Println(dir.GetSize()) // Output: 500
47 | }
48 |
--------------------------------------------------------------------------------
/structural/decorator/README.md:
--------------------------------------------------------------------------------
1 | # Decorator
2 |
3 | The Decorator design pattern allows us to add new functionalities to existing objects without altering their structures. This pattern involves a set of decorator classes that are used to wrap concrete components. Decorator classes mirror the type of the components they decorate but add or override behavior.
4 |
5 | The key feature of this pattern is the ability to "wrap" or "decorate" an object multiple times, with different decorators, adding cumulative behavior to the original object. The pattern is particularly useful for adding responsibilities to objects dynamically and optionally.
6 |
7 | Key Points:
8 |
9 | - Component Interface: This defines the interface for objects that can have responsibilities added to them dynamically.
10 | - Concrete Component: It is the object to which new responsibilities are added.
11 | - Decorator: This maintains a reference to a Component object and defines an interface that conforms to the Component's interface.
12 | - Concrete Decorators: These extend the Decorator and add specific responsibilities.
13 |
14 | ## Example
15 |
16 | Let's consider an example with input/output (I/O) operations in a system. Imagine you want to read data from a file. At its core, you just read raw bytes. But often you'll want to enhance this process with additional features such as:
17 |
18 | - Buffering: Read large chunks at once to improve performance.
19 | - Decompression: If your file is compressed, you might want to decompress it on-the-fly while reading.
20 | - Encryption: Maybe your data is encrypted, and you need to decrypt it when reading.
21 |
22 | Each of these features can be seen as a "decoration" to the basic file reading operation. Using the decorator pattern, you can dynamically construct a chain of operations for file reading.
23 |
24 | Here's an example in Go, focusing on the structure of the decorator pattern:
25 |
26 | ```go
27 | // Reader is our base component interface
28 | type Reader interface {
29 | Read() string
30 | }
31 |
32 | // FileReader reads from a file
33 | type FileReader struct{}
34 |
35 | func (fr *FileReader) Read() string {
36 | return "data from file"
37 | }
38 |
39 | // Buffered reader as a decorator
40 | type BufferedReader struct {
41 | reader Reader
42 | }
43 |
44 | func (br *BufferedReader) Read() string {
45 | data := br.reader.Read()
46 | return "buffered " + data
47 | }
48 |
49 | // Decrypt reader as another decorator
50 | type DecryptReader struct {
51 | reader Reader
52 | }
53 |
54 | func (dr *DecryptReader) Read() string {
55 | data := dr.reader.Read()
56 | return "decrypted " + data
57 | }
58 | ```
59 |
60 | In this example:
61 |
62 | - `FileReader` provides basic file reading functionality.
63 | - `BufferedReader` and `DecryptReader` are decorators that extend the base reading functionality.
64 |
65 | By using the decorator pattern, we can stack or chain these operations in any combination we want, providing great flexibility.
66 |
--------------------------------------------------------------------------------
/structural/decorator/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | // Reader is our base component interface
8 | type Reader interface {
9 | Read() string
10 | }
11 |
12 | // FileReader reads from a file
13 | type FileReader struct{}
14 |
15 | func (fr *FileReader) Read() string {
16 | return "data from file"
17 | }
18 |
19 | // Buffered reader as a decorator
20 | type BufferedReader struct {
21 | reader Reader
22 | }
23 |
24 | func (br *BufferedReader) Read() string {
25 | data := br.reader.Read()
26 | return "buffered " + data
27 | }
28 |
29 | // Decrypt reader as another decorator
30 | type DecryptReader struct {
31 | reader Reader
32 | }
33 |
34 | func (dr *DecryptReader) Read() string {
35 | data := dr.reader.Read()
36 | return "decrypted " + data
37 | }
38 |
39 | func main() {
40 | fileReader := &FileReader{}
41 |
42 | // Buffered read
43 | bufferedReader := &BufferedReader{reader: fileReader}
44 | fmt.Println(bufferedReader.Read())
45 |
46 | // Buffered and decrypted read
47 | decryptBufferedReader := &DecryptReader{reader: bufferedReader}
48 | fmt.Println(decryptBufferedReader.Read())
49 | }
50 |
--------------------------------------------------------------------------------
/structural/facade/README.md:
--------------------------------------------------------------------------------
1 | # Façade
2 |
3 | The façade design pattern provides a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use. Essentially, it simplifies a complex system by providing a single entry point to coordinate various functionalities.
4 |
5 | The main reasons to use the façade pattern are:
6 |
7 | - Simplification: It makes a complex system easier to understand and use by providing a simplified interface.
8 | - Decoupling: It decouples the subsystem from clients and other subsystems, promoting subsystem independence and portability.
9 | - Layering: You can use the façade to define an entry point to each subsystem level. This can be especially beneficial in layered architectures.
10 |
11 | The façade pattern can often be found in complex systems and frameworks to provide a simpler, more developer-friendly API. One common area in software engineering where the façade pattern is used is in the design of software libraries and frameworks.
12 |
13 | ## Example
14 |
15 | Let's say we're designing a library to interact with a database. Underneath the hood, connecting to a database might involve multiple steps: opening a connection, configuring connection parameters, setting up a session, etc. If you expose all these steps to the end developer, it can get cumbersome.
16 |
17 | Instead, you provide a simple façade that abstracts away the complexity.
18 |
19 | ```go
20 | // Complex library components
21 | type DatabaseConnection struct{}
22 |
23 | func (dc *DatabaseConnection) Open() {
24 | fmt.Println("Opening database connection...")
25 | }
26 |
27 | func (dc *DatabaseConnection) SetConfiguration() {
28 | fmt.Println("Setting configuration...")
29 | }
30 |
31 | type DatabaseSession struct{}
32 |
33 | func (ds *DatabaseSession) Init() {
34 | fmt.Println("Initializing session...")
35 | }
36 |
37 | // DatabaseFacade provides a simplified interface to interact with the database
38 | type DatabaseFacade struct {
39 | connection *DatabaseConnection
40 | session *DatabaseSession
41 | }
42 |
43 | func (df *DatabaseFacade) Start() {
44 | df.connection.Open()
45 | df.connection.SetConfiguration()
46 | df.session.Init()
47 | fmt.Println("Database started!")
48 | }
49 | ```
50 |
51 | In the above example, the `DatabaseFacade` simplifies the operations needed to start a database session. The end developer using this library doesn't need to know about the intricacies of opening a connection, setting configurations, or initializing a session. They simply use the `Start()` method provided by the façade.
52 |
53 | In real-world software systems, the underlying components can be even more complex, and the façade would abstract away a lot more intricacies. This pattern helps in making the software more maintainable and reduces the learning curve for developers unfamiliar with all the details of the underlying subsystem.
--------------------------------------------------------------------------------
/structural/facade/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Complex library components
6 | type DatabaseConnection struct{}
7 |
8 | func (dc *DatabaseConnection) Open() {
9 | fmt.Println("Opening database connection...")
10 | }
11 |
12 | func (dc *DatabaseConnection) SetConfiguration() {
13 | fmt.Println("Setting configuration...")
14 | }
15 |
16 | type DatabaseSession struct{}
17 |
18 | func (ds *DatabaseSession) Init() {
19 | fmt.Println("Initializing session...")
20 | }
21 |
22 | // DatabaseFacade provides a simplified interface to interact with the database
23 | type DatabaseFacade struct {
24 | connection *DatabaseConnection
25 | session *DatabaseSession
26 | }
27 |
28 | func (df *DatabaseFacade) Start() {
29 | df.connection.Open()
30 | df.connection.SetConfiguration()
31 | df.session.Init()
32 | fmt.Println("Database started!")
33 | }
34 |
35 | func main() {
36 | // Using the façade to simplify the database operations
37 | dbFacade := &DatabaseFacade{
38 | connection: &DatabaseConnection{},
39 | session: &DatabaseSession{},
40 | }
41 | dbFacade.Start()
42 | }
43 |
--------------------------------------------------------------------------------
/structural/flyweight/README.md:
--------------------------------------------------------------------------------
1 | # Flyweight
2 |
3 | The Flyweight Design Pattern is a structural design pattern that provides a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
4 |
5 | Flyweight pattern introduces the concept of sharing common parts of the object state among multiple objects instead of keeping all of the data in each object. The object containing the shared state is usually called a "flyweight". The pattern allows programs to support vast quantities of objects by keeping their memory consumption low.
6 |
7 | A typical use case for the Flyweight pattern is a game, for example, where you have numerous objects (trees, buildings, NPCs, etc.) and you can't afford to expend your memory resources to store each object separately with all their properties.
8 |
9 | ## Example
10 |
11 | Let's consider a simple text formatting tool. This tool would need to format different ranges of text within a document with specific styles (bold, italic, underline, etc.). These styles are shared among multiple text ranges, and each text range could be considered a unique object. The Flyweight pattern would allow us to reuse style instances instead of duplicating them for each text range, therefore saving memory.
12 |
13 | ```go
14 | // TextStyle is a flyweight that represents a specific text style.
15 | type TextStyle struct {
16 | name string
17 | }
18 |
19 | // Format applies the text style to a text.
20 | func (t *TextStyle) Format(text string) string {
21 | return fmt.Sprintf("[%s %s]", t.name, text)
22 | }
23 |
24 | // TextStyleFactory creates and manages TextStyle instances.
25 | type TextStyleFactory struct {
26 | styles map[string]*TextStyle
27 | mu sync.Mutex
28 | }
29 |
30 | // GetTextStyle returns a TextStyle instance. It reuses an existing instance if available.
31 | func (f *TextStyleFactory) GetTextStyle(name string) *TextStyle {
32 | f.mu.Lock()
33 | defer f.mu.Unlock()
34 |
35 | if style, ok := f.styles[name]; ok {
36 | return style
37 | }
38 |
39 | style := &TextStyle{name: name}
40 | f.styles[name] = style
41 | return style
42 | }
43 |
44 | // TextRange represents a range of text within a document.
45 | type TextRange struct {
46 | Start, End int
47 | Text string
48 | Style *TextStyle
49 | }
50 |
51 | // NewTextRange creates a new text range.
52 | func NewTextRange(start, end int, text string, style *TextStyle) *TextRange {
53 | return &TextRange{
54 | Start: start,
55 | End: end,
56 | Text: text,
57 | Style: style,
58 | }
59 | }
60 |
61 | // Format formats the text range with its text style.
62 | func (t *TextRange) Format() string {
63 | return t.Style.Format(t.Text)
64 | }
65 | ```
66 |
67 | In this example, `TextStyle` is a flyweight that represents a text style. `TextStyleFactory` manages the creation and reuse of `TextStyle` instances. `TextRange` represents a range of text within a document and uses a `TextStyle` to format its text. By using the Flyweight pattern, the "Bold" `TextStyle` instance is only created once and shared among multiple `TextRange` instances, thereby saving memory.
68 |
--------------------------------------------------------------------------------
/structural/flyweight/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | // TextStyle is a flyweight that represents a specific text style.
9 | type TextStyle struct {
10 | name string
11 | }
12 |
13 | // Format applies the text style to a text.
14 | func (t *TextStyle) Format(text string) string {
15 | return fmt.Sprintf("[%s %s]", t.name, text)
16 | }
17 |
18 | // TextStyleFactory creates and manages TextStyle instances.
19 | type TextStyleFactory struct {
20 | styles map[string]*TextStyle
21 | mu sync.Mutex
22 | }
23 |
24 | // GetTextStyle returns a TextStyle instance. It reuses an existing instance if available.
25 | func (f *TextStyleFactory) GetTextStyle(name string) *TextStyle {
26 | f.mu.Lock()
27 | defer f.mu.Unlock()
28 |
29 | if style, ok := f.styles[name]; ok {
30 | return style
31 | }
32 |
33 | style := &TextStyle{name: name}
34 | f.styles[name] = style
35 | return style
36 | }
37 |
38 | // TextRange represents a range of text within a document.
39 | type TextRange struct {
40 | Start, End int
41 | Text string
42 | Style *TextStyle
43 | }
44 |
45 | // NewTextRange creates a new text range.
46 | func NewTextRange(start, end int, text string, style *TextStyle) *TextRange {
47 | return &TextRange{
48 | Start: start,
49 | End: end,
50 | Text: text,
51 | Style: style,
52 | }
53 | }
54 |
55 | // Format formats the text range with its text style.
56 | func (t *TextRange) Format() string {
57 | return t.Style.Format(t.Text)
58 | }
59 |
60 | func main() {
61 | factory := &TextStyleFactory{
62 | styles: make(map[string]*TextStyle),
63 | }
64 |
65 | // Both text ranges share the same TextStyle instance.
66 | textRange1 := NewTextRange(0, 5, "Hello", factory.GetTextStyle("Bold"))
67 | textRange2 := NewTextRange(6, 11, "World", factory.GetTextStyle("Bold"))
68 |
69 | fmt.Println(textRange1.Format())
70 | fmt.Println(textRange2.Format())
71 | }
72 |
--------------------------------------------------------------------------------
/structural/proxy/README.md:
--------------------------------------------------------------------------------
1 | # Proxy
2 |
3 | The proxy design pattern provides a surrogate or placeholder for another object to control access to it. It involves a class, called the proxy, which represents the functionality of another class. The proxy pattern is useful for tasks like lazy instantiation (creating an object only when it's actually needed), permission control, and more sophisticated memory management.
4 |
5 | Here's a simple breakdown of how the proxy pattern works:
6 |
7 | - The Subject defines a common interface for the RealObject and the Proxy so that the Proxy can be used anywhere the RealObject is expected.
8 | - The RealObject defines the real object that the proxy represents.
9 | - The Proxy maintains a reference that lets the proxy access the real object. It handles requests and forwards these requests to the real object.
10 |
11 | ## Example
12 |
13 | A practical example could be a system that interacts with an external service API. Without a proxy, every part of your code that needed to communicate with the API would have to know how to do so. With a proxy, you encapsulate the communication logic in one place, making the code cleaner and easier to maintain.
14 |
15 | Let's say you have a service that retrieves user information from a third-party API. You may want to implement a caching mechanism to avoid unnecessary network requests if the same data is requested multiple times. You can implement this with the proxy pattern.
16 |
17 | ```go
18 | type User struct {
19 | ID string
20 | Name string
21 | }
22 |
23 | type UserService interface {
24 | GetUser(ID string) (*User, error)
25 | }
26 |
27 | type RealUserService struct{}
28 |
29 | func (s *RealUserService) GetUser(ID string) (*User, error) {
30 | // Simulate a real API request
31 | fmt.Println("Fetching user from API...")
32 | return &User{ID: ID, Name: "John Doe"}, nil
33 | }
34 |
35 | type CachedUserService struct {
36 | realService UserService
37 | cache map[string]*User
38 | mux sync.Mutex
39 | }
40 |
41 | func (s *CachedUserService) GetUser(ID string) (*User, error) {
42 | s.mux.Lock()
43 | defer s.mux.Unlock()
44 | if user, ok := s.cache[ID]; ok {
45 | fmt.Println("Returning user from cache...")
46 | return user, nil
47 | }
48 | user, err := s.realService.GetUser(ID)
49 | if err != nil {
50 | return nil, err
51 | }
52 | s.cache[ID] = user
53 | return user, nil
54 | }
55 |
56 | func NewCachedUserService(service UserService) UserService {
57 | return &CachedUserService{
58 | realService: service,
59 | cache: make(map[string]*User),
60 | }
61 | }
62 | ```
63 |
64 | In this example, `UserService` is the interface for the user service, `RealUserService` fetches user data from the API, and `CachedUserService` is the proxy that adds caching. If the requested user data is in the cache, `CachedUserService` returns it without calling the real service. Otherwise, it fetches the data from `RealUserService`, stores it in the cache, and then returns it.
65 |
--------------------------------------------------------------------------------
/structural/proxy/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | type User struct {
9 | ID string
10 | Name string
11 | }
12 |
13 | type UserService interface {
14 | GetUser(ID string) (*User, error)
15 | }
16 |
17 | type RealUserService struct{}
18 |
19 | func (s *RealUserService) GetUser(ID string) (*User, error) {
20 | // Simulate a real API request
21 | fmt.Println("Fetching user from API...")
22 | return &User{ID: ID, Name: "John Doe"}, nil
23 | }
24 |
25 | type CachedUserService struct {
26 | realService UserService
27 | cache map[string]*User
28 | mux sync.Mutex
29 | }
30 |
31 | func (s *CachedUserService) GetUser(ID string) (*User, error) {
32 | s.mux.Lock()
33 | defer s.mux.Unlock()
34 | if user, ok := s.cache[ID]; ok {
35 | fmt.Println("Returning user from cache...")
36 | return user, nil
37 | }
38 | user, err := s.realService.GetUser(ID)
39 | if err != nil {
40 | return nil, err
41 | }
42 | s.cache[ID] = user
43 | return user, nil
44 | }
45 |
46 | func NewCachedUserService(service UserService) UserService {
47 | return &CachedUserService{
48 | realService: service,
49 | cache: make(map[string]*User),
50 | }
51 | }
52 |
53 | func main() {
54 | service := NewCachedUserService(&RealUserService{})
55 |
56 | // Fetches from API
57 | service.GetUser("123")
58 |
59 | // Returns from cache
60 | service.GetUser("123")
61 | }
62 |
--------------------------------------------------------------------------------