[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.prof\n# Test binary, build with `go test -c`\n*.test\n# Binaries for programs and plugins\n*.exe\n*.dll\n*.dylib\n\n# JetBrains project files\n.idea/\n\n# Output of the go coverage tool, specifically when used with LiteIDE\n*.out"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\n\nenv:\n  global:\n    - GH_REPO=\"github.com/tmrts/go-patterns\"\n    - secure: SRAVBGLCkoVpCNC5J43qC6xcQvigIYbGKgLMLiP9B4XiyKH/Q6VGjk/BVVPYuC0d072jNjgfhVdTLx/jGgy6nN+AD7i8U/FoDY6pQmy4cK1nghUUlt44mq7JTlXYHLmV3NsaxmRMV5QuO9L/9AMcCh6U0MxrgMYafSPaSdHQq8hTkFFOYU05zKKUihLF3sVfEZ0KpxhHjtKA+SqcJK2NjqaGdySaziSe6Nj1kZgF9/SJkOiw/bM7O4/uqFXqEGZo5QaOQpwaj2B0wfGqwfJtyE2wM+80Aw5Ya/yqdQWplUozHKv36/u1N45cHkeDbr+RXnBpmUfGh8YTbInWh9BjyU5MLgKeJTtUMAVvwr/soa+OsHuGmdeVM5mRdXISlFSnXCkoowJ6iQsPdqGvYROz0KqqXmkVDuUKdxPU4ShyKo/LqtRwXvxQS9etF4ais8MoNmW0zI3eKdc4b6cpCXWt5fUtK8uzSUGDHHVFGpWnk8VsF0cPfLYxd9bo87amHqYGQoPJ4ughTtOAbA6uSNlcDM9AkQ591+vHpQE15td2VXUOf7aKqqPFWy+GagsI/yPry6v3d/Mk5D4ZLUXZGOv5uvengyos0dxWg9EV1yjm/mpiCtuqAtvV9HMNxcMGGCii7dMy37WmGBj3HBqeGPYHvt8pKMo2/gkcXxadzBXvJVs=\n\ninstall:\n  - npm install gitbook-cli\n  - gitbook install\n\nscript:\n  - gitbook build . out\n\nafter_success:\n  - echo -e \"Deploying updates to GitHub...\"\n  - MSG=$(git log -1 --oneline)\n  - cd out\n  - git config --global user.email \"contact@tmrts.com\"\n  - git config --global user.name \"Tamer Tas\"\n  - git init\n  - git checkout -b gh-pages\n  - git add -A :/\n  - git commit -m \"Travis CI | ${MSG}\"\n  - git push \"https://${GH_TOKEN}@${GH_REPO}\" gh-pages -f\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contribution Guidelines\n\nPlease ensure your pull request adheres to the following guidelines:\n\n- Make an individual pull request for each suggestion.\n- Choose the corresponding patterns section for your suggestion.\n- List, after your addition, should be in lexicographical order.\n\n## Commit Messages Guidelines\n\n- The message should be in imperative form and uncapitalized.\n- If possible, please include an explanation in the commit message body\n- Use the form `<pattern-section>/<pattern-name>: <message>` (e.g. `creational/singleton: refactor singleton constructor`)\n\n## Pattern Template\n\nEach pattern should have a single markdown file containing the important part of the implementation, the usage and the explanations for it. This is to ensure that the reader doesn't have to read bunch of boilerplate to understand what's going on and the code is as simple as possible and not simpler.\n\nPlease use the following template for adding new patterns:\n\n```markdown\n# <Pattern-Name>\n<Pattern description>\n\n## Implementation\n\n## Usage\n\n// Optional\n## Rules of Thumb \n```\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img src=\"/gopher.png\" height=\"400\">\n  <h1 align=\"center\">\n    Go Patterns\n    <br>\n    <a href=\"http://travis-ci.org/tmrts/go-patterns\"><img alt=\"build-status\" src=\"https://img.shields.io/badge/build-passing-brightgreen.svg?style=flat-square\" /></a>\n    <a href=\"https://github.com/sindresorhus/awesome\" ><img alt=\"awesome\" src=\"https://img.shields.io/badge/awesome-%E2%9C%93-ff69b4.svg?style=flat-square\" /></a>\n    <a href=\"https://github.com/tmrts/go-patterns/blob/master/LICENSE\" ><img alt=\"license\" src=\"https://img.shields.io/badge/license-Apache%20License%202.0-E91E63.svg?style=flat-square\" /></a>\n  </h1>\n</p>\n\nA curated collection of idiomatic design & application patterns for Go language.\n\n## Creational Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Abstract Factory](/creational/abstract_factory.md) | Provides an interface for creating families of releated objects | ✘ |\n| [Builder](/creational/builder.md) | Builds a complex object using simple objects | ✔ |\n| [Factory Method](/creational/factory.md) | Defers instantiation of an object to a specialized function for creating instances | ✔ |\n| [Object Pool](/creational/object-pool.md) | Instantiates and maintains a group of objects instances of the same type | ✔ |\n| [Singleton](/creational/singleton.md) | Restricts instantiation of a type to one object | ✔ |\n\n## Structural Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Bridge](/structural/bridge.md) | Decouples an interface from its implementation so that the two can vary independently | ✘ |\n| [Composite](/structural/composite.md) | Encapsulates and provides access to a number of different objects | ✘ |\n| [Decorator](/structural/decorator.md) | Adds behavior to an object, statically or dynamically | ✔ |\n| [Facade](/structural/facade.md) | Uses one type as an API to a number of others | ✘ |\n| [Flyweight](/structural/flyweight.md) | Reuses existing instances of objects with similar/identical state to minimize resource usage | ✘ |\n| [Proxy](/structural/proxy.md) | Provides a surrogate for an object to control it's actions | ✔ |\n\n## Behavioral Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Chain of Responsibility](/behavioral/chain_of_responsibility.md) | Avoids coupling a sender to receiver by giving more than object a chance to handle the request | ✘ |\n| [Command](/behavioral/command.md) | Bundles a command and arguments to call later | ✘ |\n| [Mediator](/behavioral/mediator.md) | Connects objects and acts as a proxy | ✘ |\n| [Memento](/behavioral/memento.md) | Generate an opaque token that can be used to go back to a previous state | ✘ |\n| [Observer](/behavioral/observer.md) | Provide a callback for notification of events/changes to data | ✔ |\n| [Registry](/behavioral/registry.md) | Keep track of all subclasses of a given class | ✘ |\n| [State](/behavioral/state.md) | Encapsulates varying behavior for the same object based on its internal state | ✘ |\n| [Strategy](/behavioral/strategy.md) | Enables an algorithm's behavior to be selected at runtime | ✔ |\n| [Template](/behavioral/template.md) | Defines a skeleton class which defers some methods to subclasses | ✘ |\n| [Visitor](/behavioral/visitor.md) | Separates an algorithm from an object on which it operates | ✘ |\n\n## Synchronization Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Condition Variable](/synchronization/condition_variable.md) | Provides a mechanism for threads to temporarily give up access in order to wait for some condition | ✘ |\n| [Lock/Mutex](/synchronization/mutex.md) | Enforces mutual exclusion limit on a resource to gain exclusive access | ✘ |\n| [Monitor](/synchronization/monitor.md) | Combination of mutex and condition variable patterns | ✘ |\n| [Read-Write Lock](/synchronization/read_write_lock.md) | Allows parallel read access, but only exclusive access on write operations to a resource | ✘ |\n| [Semaphore](/synchronization/semaphore.md) | Allows controlling access to a common resource | ✔ |\n\n## Concurrency Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [N-Barrier](/concurrency/barrier.md) | Prevents a process from proceeding until all N processes reach to the barrier | ✘ |\n| [Bounded Parallelism](/concurrency/bounded_parallelism.md) | Completes large number of independent tasks with resource limits | ✔ |\n| [Broadcast](/concurrency/broadcast.md) | Transfers a message to all recipients simultaneously | ✘ |\n| [Coroutines](/concurrency/coroutine.md) | Subroutines that allow suspending and resuming execution at certain locations | ✘ |\n| [Generators](/concurrency/generator.md) | Yields a sequence of values one at a time | ✔ |\n| [Reactor](/concurrency/reactor.md) | Demultiplexes service requests delivered concurrently to a service handler and dispatches them syncronously to the associated request handlers | ✘ |\n| [Parallelism](/concurrency/parallelism.md) | Completes large number of independent tasks | ✔ |\n| [Producer Consumer](/concurrency/producer_consumer.md) | Separates tasks from task executions | ✘ |\n\n## Messaging Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Fan-In](/messaging/fan_in.md) | Funnels tasks to a work sink (e.g. server) | ✔ |\n| [Fan-Out](/messaging/fan_out.md) | Distributes tasks among workers (e.g. producer) | ✔ |\n| [Futures & Promises](/messaging/futures_promises.md) | Acts as a place-holder of a result that is initially unknown for synchronization purposes | ✘ |\n| [Publish/Subscribe](/messaging/publish_subscribe.md) | Passes information to a collection of recipients who subscribed to a topic | ✔ |\n| [Push & Pull](/messaging/push_pull.md) | Distributes messages to multiple workers, arranged in a pipeline | ✘ |\n\n## Stability Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Bulkheads](/stability/bulkhead.md)  | Enforces a principle of failure containment (i.e. prevents cascading failures) | ✘ |\n| [Circuit-Breaker](/stability/circuit-breaker.md) | Stops the flow of the requests when requests are likely to fail | ✔ |\n| [Deadline](/stability/deadline.md) | Allows clients to stop waiting for a response once the probability of response becomes low (e.g. after waiting 10 seconds for a page refresh) | ✘ |\n| [Fail-Fast](/stability/fail_fast.md) | Checks the availability of required resources at the start of a request and fails if the requirements are not satisfied | ✘ |\n| [Handshaking](/stability/handshaking.md) | Asks a component if it can take any more load, if it can't, the request is declined | ✘ |\n| [Steady-State](/stability/steady_state.md) | For every service that accumulates a resource, some other service must recycle that resource | ✘ |\n\n## Profiling Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Timing Functions](/profiling/timing.md) | Wraps a function and logs the execution | ✔ |\n\n## Idioms\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Functional Options](/idiom/functional-options.md) | Allows creating clean APIs with sane defaults and idiomatic overrides | ✔ |\n\n## Anti-Patterns\n\n| Pattern | Description | Status |\n|:-------:|:----------- |:------:|\n| [Cascading Failures](/anti-patterns/cascading_failures.md) | A failure in a system of interconnected parts in which the failure of a part causes a domino effect | ✘ |\n"
  },
  {
    "path": "SUMMARY.md",
    "content": "# Summary\n\n* [Go Patterns](/README.md)\n  * [Creational Patterns](/README.md#creational-patterns)\n    * [Abstract Factory](/creational/abstract_factory.md)\n    * [Builder](/creational/builder.md)\n    * [Factory Method](/creational/factory.md)\n    * [Object Pool](/creational/object-pool.md)\n    * [Singleton](/creational/singleton.md)\n  * [Structural Patterns](/README.md#structural-patterns)\n    * [Bridge](/structural/bridge.md)\n    * [Composite](/structural/composite.md)\n    * [Decorator](/structural/decorator.md)\n    * [Facade](/structural/facade.md)\n    * [Flyweight](/structural/flyweight.md)\n    * [Proxy](/structural/proxy.md)\n  * [Behavioral Patterns](/README.md#behavioral-patterns)\n    * [Chain of Responsibility](/behavioral/chain_of_responsibility.md)\n    * [Command](/behavioral/command.md)\n    * [Mediator](/behavioral/mediator.md)\n    * [Memento](/behavioral/memento.md)\n    * [Observer](/behavioral/observer.md)\n    * [Registry](/behavioral/registry.md)\n    * [State](/behavioral/state.md)\n    * [Strategy](/behavioral/strategy.md)\n    * [Template](/behavioral/template.md)\n    * [Visitor](/behavioral/visitor.md)\n  * [Synchronization Patterns](/README.md#synchronization-patterns)\n    * [Condition Variable](/synchronization/condition_variable.md)\n    * [Lock/Mutex](/synchronization/mutex.md)\n    * [Monitor](/synchronization/monitor.md)\n    * [Read-Write Lock](/synchronization/read_write_lock.md)\n    * [Semaphore](/synchronization/semaphore.md)\n  * [Concurrency Patterns](/README.md#concurrency-patterns)\n    * [N-Barrier](/concurrency/barrier.md)\n    * [Bounded Parallelism](/concurrency/bounded_parallelism.md)\n    * [Broadcast](/concurrency/broadcast.md)\n    * [Coroutines](/concurrency/coroutine.md)\n    * [Generators](/concurrency/generator.md)\n    * [Reactor](/concurrency/reactor.md)\n    * [Parallelism](/concurrency/parallelism.md)\n    * [Producer Consumer](/concurrency/producer_consumer.md)\n  * [Messaging Patterns](/README.md#messaging-patterns)\n    * [Fan-In](/messaging/fan_in.md)\n    * [Fan-Out](/messaging/fan_out.md)\n    * [Futures & Promises](/messaging/futures_promises.md)\n    * [Publish/Subscribe](/messaging/publish_subscribe.md)\n    * [Push & Pull](/messaging/push_pull.md)\n  * [Stability Patterns](/README.md#stability-patterns)\n    * [Bulkheads](/stability/bulkhead.md)\n    * [Circuit-Breaker](/stability/circuit-breaker.md)\n    * [Deadline](/stability/deadline.md)\n    * [Fail-Fast](/stability/fail_fast.md)\n    * [Handshaking](/stability/handshaking.md)\n    * [Steady-State](/stability/steady_state.md)\n  * [Profiling Patterns](/README.md#profiling-patterns)\n    * [Timing Functions](/profiling/timing.md)\n  * [Idioms](/README.md#idioms)\n    * [Functional Options](/idiom/functional-options.md)\n  * [Anti-Patterns](/README.md#anti-patterns)\n    * [Cascading Failures](/anti-patterns/cascading_failures.md)\n* [Contributing](/CONTRIBUTING.md)\n"
  },
  {
    "path": "behavioral/observer/main.go",
    "content": "// Package main serves as an example application that makes use of the observer pattern.\n// Playground: https://play.golang.org/p/cr8jEmDmw0\npackage main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype (\n\t// Event defines an indication of a point-in-time occurrence.\n\tEvent struct {\n\t\t// Data in this case is a simple int, but the actual\n\t\t// implementation would depend on the application.\n\t\tData int64\n\t}\n\n\t// Observer defines a standard interface for instances that wish to list for\n\t// the occurrence of a specific event.\n\tObserver interface {\n\t\t// OnNotify allows an event to be \"published\" to interface implementations.\n\t\t// In the \"real world\", error handling would likely be implemented.\n\t\tOnNotify(Event)\n\t}\n\n\t// Notifier is the instance being observed. Publisher is perhaps another decent\n\t// name, but naming things is hard.\n\tNotifier interface {\n\t\t// Register allows an instance to register itself to listen/observe\n\t\t// events.\n\t\tRegister(Observer)\n\t\t// Deregister allows an instance to remove itself from the collection\n\t\t// of observers/listeners.\n\t\tDeregister(Observer)\n\t\t// Notify publishes new events to listeners. The method is not\n\t\t// absolutely necessary, as each implementation could define this itself\n\t\t// without losing functionality.\n\t\tNotify(Event)\n\t}\n)\n\ntype (\n\teventObserver struct{\n\t\tid int\n\t}\n\n\teventNotifier struct{\n\t\t// Using a map with an empty struct allows us to keep the observers\n\t\t// unique while still keeping memory usage relatively low.\n\t\tobservers map[Observer]struct{}\n\t}\n)\n\nfunc (o *eventObserver) OnNotify(e Event) {\n\tfmt.Printf(\"*** Observer %d received: %d\\n\", o.id, e.Data)\n}\n\nfunc (o *eventNotifier) Register(l Observer) {\n\to.observers[l] = struct{}{}\n}\n\nfunc (o *eventNotifier) Deregister(l Observer) {\n\tdelete(o.observers, l)\n}\n\nfunc (p *eventNotifier) Notify(e Event) {\n\tfor o := range p.observers {\n\t\to.OnNotify(e)\n\t}\n}\n\nfunc main() {\n\t// Initialize a new Notifier.\n\tn := eventNotifier{\n\t\tobservers: map[Observer]struct{}{},\n\t}\n\n\t// Register a couple of observers.\n\tn.Register(&eventObserver{id: 1})\n\tn.Register(&eventObserver{id: 2})\n\n\t// A simple loop publishing the current Unix timestamp to observers.\n\tstop := time.NewTimer(10 * time.Second).C\n\ttick := time.NewTicker(time.Second).C\n\tfor {\n\t\tselect {\n\t\tcase <- stop:\n\t\t\treturn\n\t\tcase t := <-tick:\n\t\t\tn.Notify(Event{Data: t.UnixNano()})\n\t\t}\n\t}\n}"
  },
  {
    "path": "behavioral/observer.md",
    "content": "# Observer Pattern\n\nThe [observer pattern](https://en.wikipedia.org/wiki/Observer_pattern) allows a type instance to \"publish\" events to other type instances (\"observers\") who wish to be updated when a particular event occurs.\n\n## Implementation\n\nIn long-running applications&mdash;such as webservers&mdash;instances can keep a collection of observers that will receive notification of triggered events.\n\nImplementations vary, but interfaces can be used to make standard observers and notifiers:\n\n```go\ntype (\n\t// Event defines an indication of a point-in-time occurrence.\n\tEvent struct {\n\t\t// Data in this case is a simple int, but the actual\n\t\t// implementation would depend on the application.\n\t\tData int64\n\t}\n\n\t// Observer defines a standard interface for instances that wish to list for\n\t// the occurrence of a specific event.\n\tObserver interface {\n\t\t// OnNotify allows an event to be \"published\" to interface implementations.\n\t\t// In the \"real world\", error handling would likely be implemented.\n\t\tOnNotify(Event)\n\t}\n\n\t// Notifier is the instance being observed. Publisher is perhaps another decent\n\t// name, but naming things is hard.\n\tNotifier interface {\n\t\t// Register allows an instance to register itself to listen/observe\n\t\t// events.\n\t\tRegister(Observer)\n\t\t// Deregister allows an instance to remove itself from the collection\n\t\t// of observers/listeners.\n\t\tDeregister(Observer)\n\t\t// Notify publishes new events to listeners. The method is not\n\t\t// absolutely necessary, as each implementation could define this itself\n\t\t// without losing functionality.\n\t\tNotify(Event)\n\t}\n)\n```\n\n## Usage\n\nFor usage, see [observer/main.go](observer/main.go) or [view in the Playground](https://play.golang.org/p/cr8jEmDmw0).\n"
  },
  {
    "path": "behavioral/strategy.md",
    "content": "# Strategy Pattern\nStrategy behavioral design pattern enables an algorithm's behavior to be selected at runtime.\n\nIt defines algorithms, encapsulates them, and uses them interchangeably.\n\n## Implementation\nImplementation of an interchangeable operator object that operates on integers.\n\n```go\ntype Operator interface {\n\tApply(int, int) int\n}\n\ntype Operation struct {\n\tOperator Operator\n}\n\nfunc (o *Operation) Operate(leftValue, rightValue int) int {\n\treturn o.Operator.Apply(leftValue, rightValue)\n}\n```\n\n## Usage\n### Addition Operator\n```go\ntype Addition struct{}\n\nfunc (Addition) Apply(lval, rval int) int {\n\treturn lval + rval\n}\n```\n\n```go\nadd := Operation{Addition{}}\nadd.Operate(3, 5) // 8\n```\n\n### Multiplication Operator\n```go\ntype Multiplication struct{}\n\nfunc (Multiplication) Apply(lval, rval int) int {\n\treturn lval * rval\n}\n```\n\n```go\nmult := Operation{Multiplication{}}\n\nmult.Operate(3, 5) // 15\n```\n\n## Rules of Thumb\n- Strategy pattern is similar to Template pattern except in its granularity.\n- Strategy pattern lets you change the guts of an object. Decorator pattern lets you change the skin.\n"
  },
  {
    "path": "book.json",
    "content": "{\n    \"plugins\": [\n        \"-search\", \n        \"-lunr\",\n        \"github\",\n        \"edit-link\"\n    ],\n    \"pluginsConfig\": {\n        \"github\": {\n            \"url\": \"https://github.com/tmrts/go-patterns\"\n        },\n        \"edit-link\": {\n            \"base\": \"https://github.com/tmrts/go-patterns/edit/master/\",\n            \"label\": \"\"\n        }\n    }\n}\n"
  },
  {
    "path": "concurrency/bounded_parallelism.go",
    "content": "package bounded_parallelism\n\nimport (\n\t\"crypto/md5\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"sync\"\n)\n\n// walkFiles starts a goroutine to walk the directory tree at root and send the\n// path of each regular file on the string channel.  It sends the result of the\n// walk on the error channel.  If done is closed, walkFiles abandons its work.\nfunc walkFiles(done <-chan struct{}, root string) (<-chan string, <-chan error) {\n\tpaths := make(chan string)\n\terrc := make(chan error, 1)\n\tgo func() { // HL\n\t\t// Close the paths channel after Walk returns.\n\t\tdefer close(paths) // HL\n\t\t// No select needed for this send, since errc is buffered.\n\t\terrc <- filepath.Walk(root, func(path string, info os.FileInfo, err error) error { // HL\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !info.Mode().IsRegular() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase paths <- path: // HL\n\t\t\tcase <-done: // HL\n\t\t\t\treturn errors.New(\"walk canceled\")\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}()\n\treturn paths, errc\n}\n\n// A result is the product of reading and summing a file using MD5.\ntype result struct {\n\tpath string\n\tsum  [md5.Size]byte\n\terr  error\n}\n\n// digester reads path names from paths and sends digests of the corresponding\n// files on c until either paths or done is closed.\nfunc digester(done <-chan struct{}, paths <-chan string, c chan<- result) {\n\tfor path := range paths { // HLpaths\n\t\tdata, err := ioutil.ReadFile(path)\n\t\tselect {\n\t\tcase c <- result{path, md5.Sum(data), err}:\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// MD5All reads all the files in the file tree rooted at root and returns a map\n// from file path to the MD5 sum of the file's contents.  If the directory walk\n// fails or any read operation fails, MD5All returns an error.  In that case,\n// MD5All does not wait for inflight read operations to complete.\nfunc MD5All(root string) (map[string][md5.Size]byte, error) {\n\t// MD5All closes the done channel when it returns; it may do so before\n\t// receiving all the values from c and errc.\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\tpaths, errc := walkFiles(done, root)\n\n\t// Start a fixed number of goroutines to read and digest files.\n\tc := make(chan result) // HLc\n\tvar wg sync.WaitGroup\n\tconst numDigesters = 20\n\twg.Add(numDigesters)\n\tfor i := 0; i < numDigesters; i++ {\n\t\tgo func() {\n\t\t\tdigester(done, paths, c) // HLc\n\t\t\twg.Done()\n\t\t}()\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(c) // HLc\n\t}()\n\t// End of pipeline. OMIT\n\n\tm := make(map[string][md5.Size]byte)\n\tfor r := range c {\n\t\tif r.err != nil {\n\t\t\treturn nil, r.err\n\t\t}\n\t\tm[r.path] = r.sum\n\t}\n\t// Check whether the Walk failed.\n\tif err := <-errc; err != nil { // HLerrc\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\nfunc main() {\n\t// Calculate the MD5 sum of all files under the specified directory,\n\t// then print the results sorted by path name.\n\tm, err := MD5All(os.Args[1])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tvar paths []string\n\tfor path := range m {\n\t\tpaths = append(paths, path)\n\t}\n\tsort.Strings(paths)\n\tfor _, path := range paths {\n\t\tfmt.Printf(\"%x  %s\\n\", m[path], path)\n\t}\n}\n"
  },
  {
    "path": "concurrency/bounded_parallelism.md",
    "content": "# Bounded Parallelism Pattern\n\n[Bounded parallelism](https://blog.golang.org/pipelines#TOC_9.) is similar to [parallelism](parallelism.md), but allows limits to be placed on allocation.\n\n# Implementation and Example\n\nAn example showing implementation and usage can be found in [bounded_parallelism.go](bounded_parallelism.go)."
  },
  {
    "path": "concurrency/generator.md",
    "content": "# Generator Pattern\n\n[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time.\n\n## Implementation \n\n```go\nfunc Count(start int, end int) chan int {\n    ch := make(chan int)\n\n    go func(ch chan int) {\n        for i := start; i <= end ; i++ {\n            // Blocks on the operation\n            ch <- i\n        }\n\n\t\tclose(ch)\n\t}(ch)\n\n\treturn ch\n}\n```\n\n## Usage\n\n```go\nfmt.Println(\"No bottles of beer on the wall\")\n\nfor i := range Count(1, 99) {\n    fmt.Println(\"Pass it around, put one up,\", i, \"bottles of beer on the wall\")\n    // Pass it around, put one up, 1 bottles of beer on the wall\n    // Pass it around, put one up, 2 bottles of beer on the wall\n    // ...\n    // Pass it around, put one up, 99 bottles of beer on the wall\n}\n\nfmt.Println(100, \"bottles of beer on the wall\")\n```\n"
  },
  {
    "path": "concurrency/parallelism.go",
    "content": "package parallelism\n\nimport (\n\t\"crypto/md5\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"sync\"\n)\n\n// A result is the product of reading and summing a file using MD5.\ntype result struct {\n\tpath string\n\tsum  [md5.Size]byte\n\terr  error\n}\n\n// sumFiles starts goroutines to walk the directory tree at root and digest each\n// regular file.  These goroutines send the results of the digests on the result\n// channel and send the result of the walk on the error channel.  If done is\n// closed, sumFiles abandons its work.\nfunc sumFiles(done <-chan struct{}, root string) (<-chan result, <-chan error) {\n\t// For each regular file, start a goroutine that sums the file and sends\n\t// the result on c.  Send the result of the walk on errc.\n\tc := make(chan result)\n\terrc := make(chan error, 1)\n\tgo func() { // HL\n\t\tvar wg sync.WaitGroup\n\t\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !info.Mode().IsRegular() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\twg.Add(1)\n\t\t\tgo func() { // HL\n\t\t\t\tdata, err := ioutil.ReadFile(path)\n\t\t\t\tselect {\n\t\t\t\tcase c <- result{path, md5.Sum(data), err}: // HL\n\t\t\t\tcase <-done: // HL\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t\t// Abort the walk if done is closed.\n\t\t\tselect {\n\t\t\tcase <-done: // HL\n\t\t\t\treturn errors.New(\"walk canceled\")\n\t\t\tdefault:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t})\n\t\t// Walk has returned, so all calls to wg.Add are done.  Start a\n\t\t// goroutine to close c once all the sends are done.\n\t\tgo func() { // HL\n\t\t\twg.Wait()\n\t\t\tclose(c) // HL\n\t\t}()\n\t\t// No select needed here, since errc is buffered.\n\t\terrc <- err // HL\n\t}()\n\treturn c, errc\n}\n\n// MD5All reads all the files in the file tree rooted at root and returns a map\n// from file path to the MD5 sum of the file's contents.  If the directory walk\n// fails or any read operation fails, MD5All returns an error.  In that case,\n// MD5All does not wait for inflight read operations to complete.\nfunc MD5All(root string) (map[string][md5.Size]byte, error) {\n\t// MD5All closes the done channel when it returns; it may do so before\n\t// receiving all the values from c and errc.\n\tdone := make(chan struct{}) // HLdone\n\tdefer close(done)           // HLdone\n\n\tc, errc := sumFiles(done, root) // HLdone\n\n\tm := make(map[string][md5.Size]byte)\n\tfor r := range c { // HLrange\n\t\tif r.err != nil {\n\t\t\treturn nil, r.err\n\t\t}\n\t\tm[r.path] = r.sum\n\t}\n\tif err := <-errc; err != nil {\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}\n\nfunc main() {\n\t// Calculate the MD5 sum of all files under the specified directory,\n\t// then print the results sorted by path name.\n\tm, err := MD5All(os.Args[1])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tvar paths []string\n\tfor path := range m {\n\t\tpaths = append(paths, path)\n\t}\n\tsort.Strings(paths)\n\tfor _, path := range paths {\n\t\tfmt.Printf(\"%x  %s\\n\", m[path], path)\n\t}\n}\n"
  },
  {
    "path": "concurrency/parallelism.md",
    "content": "# Parallelism Pattern\n\n[Parallelism](https://blog.golang.org/pipelines#TOC_8.) allows multiple \"jobs\" or tasks to be run concurrently and asynchronously.\n\n# Implementation and Example\n\nAn example showing implementation and usage can be found in [parallelism.go](parallelism.go)."
  },
  {
    "path": "creational/builder.md",
    "content": "# Builder Pattern\n\nBuilder pattern separates the construction of a complex object from its\nrepresentation so that the same construction process can create different\nrepresentations.\n\nIn Go, normally a configuration struct is used to achieve the same behavior,\nhowever passing a struct to the builder method fills the code with boilerplate\n`if cfg.Field != nil {...}` checks.\n\n## Implementation\n\n```go\npackage car\n\ntype Speed float64\n\nconst (\n    MPH Speed = 1\n    KPH       = 1.60934\n)\n\ntype Color string\n\nconst (\n    BlueColor  Color = \"blue\"\n    GreenColor       = \"green\"\n    RedColor         = \"red\"\n)\n\ntype Wheels string\n\nconst (\n    SportsWheels Wheels = \"sports\"\n    SteelWheels         = \"steel\"\n)\n\ntype Builder interface {\n    Color(Color) Builder\n    Wheels(Wheels) Builder\n    TopSpeed(Speed) Builder\n    Build() Interface\n}\n\ntype Interface interface {\n    Drive() error\n    Stop() error\n}\n```\n\n## Usage\n\n```go\nassembly := car.NewBuilder().Paint(car.RedColor)\n\nfamilyCar := assembly.Wheels(car.SportsWheels).TopSpeed(50 * car.MPH).Build()\nfamilyCar.Drive()\n\nsportsCar := assembly.Wheels(car.SteelWheels).TopSpeed(150 * car.MPH).Build()\nsportsCar.Drive()\n```\n"
  },
  {
    "path": "creational/factory.md",
    "content": "# Factory Method Pattern\n\nFactory method creational design pattern allows creating objects without having\nto specify the exact type of the object that will be created.\n\n## Implementation\n\nThe example implementation shows how to provide a data store with different\nbackends such as in-memory, disk storage.\n\n### Types\n\n```go\npackage data\n\nimport \"io\"\n\ntype Store interface {\n    Open(string) (io.ReadWriteCloser, error)\n}\n```\n\n### Different Implementations\n\n```go\npackage data\n\ntype StorageType int\n\nconst (\n    DiskStorage StorageType = 1 << iota\n    TempStorage\n    MemoryStorage\n)\n\nfunc NewStore(t StorageType) Store {\n    switch t {\n    case MemoryStorage:\n        return newMemoryStorage( /*...*/ )\n    case DiskStorage:\n        return newDiskStorage( /*...*/ )\n    default:\n        return newTempStorage( /*...*/ )\n    }\n}\n```\n\n## Usage\n\nWith the factory method, the user can specify the type of storage they want.\n\n```go\ns, _ := data.NewStore(data.MemoryStorage)\nf, _ := s.Open(\"file\")\n\nn, _ := f.Write([]byte(\"data\"))\ndefer f.Close()\n```\n"
  },
  {
    "path": "creational/object-pool.md",
    "content": "# Object Pool Pattern\n\nThe object pool creational design pattern is used to prepare and keep multiple\ninstances according to the demand expectation.\n\n## Implementation\n\n```go\npackage pool\n\ntype Pool chan *Object\n\nfunc New(total int) *Pool {\n\tp := make(Pool, total)\n\n\tfor i := 0; i < total; i++ {\n\t\tp <- new(Object)\n\t}\n\n\treturn &p\n}\n```\n\n## Usage\n\nGiven below is a simple lifecycle example on an object pool.\n\n```go\np := pool.New(2)\n\nselect {\ncase obj := <-p:\n\tobj.Do( /*...*/ )\n\n\tp <- obj\ndefault:\n\t// No more objects left — retry later or fail\n\treturn\n}\n```\n\n## Rules of Thumb\n\n- Object pool pattern is useful in cases where object initialization is more\n  expensive than the object maintenance.\n- If there are spikes in demand as opposed to a steady demand, the maintenance\n  overhead might overweigh the benefits of an object pool.\n- It has positive effects on performance due to objects being initialized beforehand.\n"
  },
  {
    "path": "creational/singleton.md",
    "content": "# Singleton Pattern\n\nSingleton creational design pattern restricts the instantiation of a type to a single object.\n\n## Implementation\n\n```go\npackage singleton\n\ntype singleton map[string]string\n\nvar (\n    once sync.Once\n\n    instance singleton\n)\n\nfunc New() singleton {\n\tonce.Do(func() {\n\t\tinstance = make(singleton)\n\t})\n\n\treturn instance\n}\n```\n\n## Usage\n\n```go\ns := singleton.New()\n\ns[\"this\"] = \"that\"\n\ns2 := singleton.New()\n\nfmt.Println(\"This is \", s2[\"this\"])\n// This is that\n```\n\n## Rules of Thumb\n\n- Singleton pattern represents a global state and most of the time reduces testability.\n"
  },
  {
    "path": "idiom/functional-options.md",
    "content": "# Functional Options\n\nFunctional options are a method of implementing clean/eloquent APIs in Go.\nOptions implemented as a function set the state of that option.\n\n## Implementation\n\n### Options\n\n```go\npackage file\n\ntype Options struct {\n\tUID         int\n\tGID         int\n\tFlags       int\n\tContents    string\n\tPermissions os.FileMode\n}\n\ntype Option func(*Options)\n\nfunc UID(userID int) Option {\n\treturn func(args *Options) {\n\t\targs.UID = userID\n\t}\n}\n\nfunc GID(groupID int) Option {\n\treturn func(args *Options) {\n\t\targs.GID = groupID\n\t}\n}\n\nfunc Contents(c string) Option {\n\treturn func(args *Options) {\n\t\targs.Contents = c\n\t}\n}\n\nfunc Permissions(perms os.FileMode) Option {\n\treturn func(args *Options) {\n\t\targs.Permissions = perms\n\t}\n}\n```\n\n### Constructor\n\n```go\npackage file\n\nfunc New(filepath string, setters ...Option) error {\n\t// Default Options\n\targs := &Options{\n\t\tUID:         os.Getuid(),\n\t\tGID:         os.Getgid(),\n\t\tContents:    \"\",\n\t\tPermissions: 0666,\n\t\tFlags:       os.O_CREATE | os.O_EXCL | os.O_WRONLY,\n\t}\n\n\tfor _, setter := range setters {\n\t\tsetter(args)\n\t}\n\n\tf, err := os.OpenFile(filepath, args.Flags, args.Permissions)\n\tif err != nil {\n\t\treturn err\n\t} else {\n\t\tdefer f.Close()\n\t}\n\n\tif _, err := f.WriteString(args.Contents); err != nil {\n\t\treturn err\n\t}\n\n\treturn f.Chown(args.UID, args.GID)\n}\n```\n\n## Usage\n\n```go\nemptyFile, err := file.New(\"/tmp/empty.txt\")\nif err != nil {\n    panic(err)\n}\n\nfillerFile, err := file.New(\"/tmp/file.txt\", file.UID(1000), file.Contents(\"Lorem Ipsum Dolor Amet\"))\nif err != nil {\n    panic(err)\n}\n```\n"
  },
  {
    "path": "messaging/fan_in.md",
    "content": "Fan-In Messaging Patterns\n===================================\nFan-In is a messaging pattern used to create a funnel for work amongst workers (clients: source, server: destination).\n\nWe can model fan-in using the Go channels.\n\n```go\n// Merge different channels in one channel\nfunc Merge(cs ...<-chan int) <-chan int {\n\tvar wg sync.WaitGroup\n\n\tout := make(chan int)\n\n\t// Start an send goroutine for each input channel in cs. send\n\t// copies values from c to out until c is closed, then calls wg.Done.\n\tsend := func(c <-chan int) {\n\t\tfor n := range c {\n\t\t\tout <- n\n\t\t}\n\t\twg.Done()\n\t}\n\n\twg.Add(len(cs))\n\tfor _, c := range cs {\n\t\tgo send(c)\n\t}\n\n\t// Start a goroutine to close out once all the send goroutines are\n\t// done.  This must start after the wg.Add call.\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n\treturn out\n}\n```\n\nThe `Merge` function converts a list of channels to a single channel by starting a goroutine for each inbound channel that copies the values to the sole outbound channel.\n\nOnce all the output goroutines have been started, `Merge` a goroutine is started to close the main channel.\n"
  },
  {
    "path": "messaging/fan_out.md",
    "content": "Fan-Out Messaging Pattern\n=========================\nFan-Out is a messaging pattern used for distributing work amongst workers (producer: source, consumers: destination).\n\nWe can model fan-out using the Go channels.\n\n```go\n// Split a channel into n channels that receive messages in a round-robin fashion.\nfunc Split(ch <-chan int, n int) []<-chan int {\n\tcs := make([]chan int)\n\tfor i := 0; i < n; i++ {\n\t\tcs = append(cs, make(chan int))\n\t}\n\n\t// Distributes the work in a round robin fashion among the stated number\n\t// of channels until the main channel has been closed. In that case, close\n\t// all channels and return.\n\tdistributeToChannels := func(ch <-chan int, cs []chan<- int) {\n\t\t// Close every channel when the execution ends.\n\t\tdefer func(cs []chan<- int) {\n\t\t\tfor _, c := range cs {\n\t\t\t\tclose(c)\n\t\t\t}\n\t\t}(cs)\n\n\t\tfor {\n\t\t\tfor _, c := range cs {\n\t\t\t\tselect {\n\t\t\t\tcase val, ok := <-ch:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tc <- val\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tgo distributeToChannels(ch, cs)\n\n\treturn cs\n}\n```\n\nThe `Split` function converts a single channel into a list of channels by using \na goroutine to copy received values to channels in the list in a round-robin fashion.\n"
  },
  {
    "path": "messaging/publish_subscribe.md",
    "content": "Publish & Subscribe Messaging Pattern\n============\nPublish-Subscribe is a messaging pattern used to communicate messages between \ndifferent components without these components knowing anything about each other's identity.\n\nIt is similar to the Observer behavioral design pattern. \nThe fundamental design principals of both Observer and Publish-Subscribe is the decoupling of\nthose interested in being informed about `Event Messages` from the informer (Observers or Publishers).\nMeaning that you don't have to program the messages to be sent directly to specific receivers.\n\nTo accomplish this, an intermediary, called a \"message broker\" or \"event bus\", \nreceives published messages, and then routes them on to subscribers.\n\n\nThere are three components **messages**, **topics**, **users**.\n\n```go\ntype Message struct {\n    // Contents\n}\n\n\ntype Subscription struct {\n\tch chan<- Message\n\n\tInbox chan Message\n}\n\nfunc (s *Subscription) Publish(msg Message) error {\n\tif _, ok := <-s.ch; !ok {\n\t\treturn errors.New(\"Topic has been closed\")\n\t}\n\n\ts.ch <- msg\n\n\treturn nil\n}\n```\n\n```go\ntype Topic struct {\n\tSubscribers    []Session\n\tMessageHistory []Message\n}\n\nfunc (t *Topic) Subscribe(uid uint64) (Subscription, error) {\n    // Get session and create one if it's the first\n\n    // Add session to the Topic & MessageHistory\n\n    // Create a subscription\n}\n\nfunc (t *Topic) Unsubscribe(Subscription) error {\n\t// Implementation\n}\n\nfunc (t *Topic) Delete() error {\n\t// Implementation\n}\n```\n\n```go\ntype User struct {\n    ID uint64\n    Name string\n}\n\ntype Session struct {\n    User User\n    Timestamp time.Time\n}\n```\n\nImprovements\n============\nEvents can be published in a parallel fashion by utilizing stackless goroutines.\n\nPerformance can be improved by dealing with straggler subscribers\nby using a buffered inbox and you stop sending events once the inbox is full.\n"
  },
  {
    "path": "profiling/timing.md",
    "content": "# Timing Functions\n\nWhen optimizing code, sometimes a quick and dirty time measurement is required\nas opposed to utilizing profiler tools/frameworks to validate assumptions.\n\nTime measurements can be performed by utilizing `time` package and `defer` statements.\n\n## Implementation\n\n```go\npackage profile\n\nimport (\n    \"time\"\n    \"log\"\n)\n\nfunc Duration(invocation time.Time, name string) {\n    elapsed := time.Since(invocation)\n\n    log.Printf(\"%s lasted %s\", name, elapsed)\n}\n```\n\n## Usage\n\n```go\nfunc BigIntFactorial(x big.Int) *big.Int {\n    // Arguments to a defer statement is immediately evaluated and stored.\n    // The deferred function receives the pre-evaluated values when its invoked.\n    defer profile.Duration(time.Now(), \"IntFactorial\")\n\n    y := big.NewInt(1)\n    for one := big.NewInt(1); x.Sign() > 0; x.Sub(x, one) {\n        y.Mul(y, x)\n    }\n\n    return x.Set(y)\n}\n```\n"
  },
  {
    "path": "stability/circuit-breaker.md",
    "content": "# Circuit Breaker Pattern\n\nSimilar to electrical fuses that prevent fires when a circuit that is connected\nto the electrical grid starts drawing a high amount of power which causes the\nwires to heat up and combust, the circuit breaker design pattern is a fail-first\nmechanism that shuts down the circuit, request/response relationship or a\nservice in the case of software development, to prevent bigger failures.\n\n**Note:** The words \"circuit\" and \"service\" are used synonymously throught this\ndocument.\n\n## Implementation\n\nBelow is the implementation of a very simple circuit breaker to illustrate the purpose\nof the circuit breaker design pattern.\n\n### Operation Counter\n\n`circuit.Counter` is a simple counter that records success and failure states of\na circuit along with a timestamp and calculates the consecutive number of\nfailures.\n\n```go\npackage circuit\n\nimport (\n\t\"time\"\n)\n\ntype State int\n\nconst (\n\tUnknownState State = iota\n\tFailureState\n\tSuccessState\n)\n\ntype Counter interface {\n\tCount(State)\n\tConsecutiveFailures() uint32\n\tLastActivity() time.Time\n\tReset()\n}\n```\n\n### Circuit Breaker\n\nCircuit is wrapped using the `circuit.Breaker` closure that keeps an internal operation counter.\nIt returns a fast error if the circuit has failed consecutively more than the specified threshold.\nAfter a while it retries the request and records it.\n\n**Note:** Context type is used here to carry deadlines, cancelation signals, and\nother request-scoped values across API boundaries and between processes.\n\n```go\npackage circuit\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\ntype Circuit func(context.Context) error\n\nfunc Breaker(c Circuit, failureThreshold uint32) Circuit {\n\tcnt := NewCounter()\n\n\treturn func(ctx context) error {\n\t\tif cnt.ConsecutiveFailures() >= failureThreshold {\n\t\t\tcanRetry := func(cnt Counter) {\n\t\t\t\tbackoffLevel := Cnt.ConsecutiveFailures() - failureThreshold\n\n\t\t\t\t// Calculates when should the circuit breaker resume propagating requests\n\t\t\t\t// to the service\n\t\t\t\tshouldRetryAt := cnt.LastActivity().Add(time.Seconds * 2 << backoffLevel)\n\n\t\t\t\treturn time.Now().After(shouldRetryAt)\n\t\t\t}\n\n\t\t\tif !canRetry(cnt) {\n\t\t\t\t// Fails fast instead of propagating requests to the circuit since\n\t\t\t\t// not enough time has passed since the last failure to retry\n\t\t\t\treturn ErrServiceUnavailable\n\t\t\t}\n\t\t}\n\n\t\t// Unless the failure threshold is exceeded the wrapped service mimics the\n\t\t// old behavior and the difference in behavior is seen after consecutive failures\n\t\tif err := c(ctx); err != nil {\n\t\t\tcnt.Count(FailureState)\n\t\t\treturn err\n\t\t}\n\n\t\tcnt.Count(SuccessState)\n\t\treturn nil\n\t}\n}\n```\n\n## Related Works\n\n- [sony/gobreaker](https://github.com/sony/gobreaker) is a well-tested and intuitive circuit breaker implementation for real-world use cases.\n"
  },
  {
    "path": "structural/decorator.md",
    "content": "# Decorator Pattern\nDecorator structural pattern allows extending the function of an existing object dynamically without altering its internals.\n\nDecorators provide a flexible method to extend functionality of objects.\n\n## Implementation\n`LogDecorate` decorates a function with the signature `func(int) int` that \nmanipulates integers and adds input/output logging capabilities.\n\n```go\ntype Object func(int) int\n\nfunc LogDecorate(fn Object) Object {\n\treturn func(n int) int {\n\t\tlog.Println(\"Starting the execution with the integer\", n)\n\n\t\tresult := fn(n)\n\n\t\tlog.Println(\"Execution is completed with the result\", result)\n\n        return result\n\t}\n}\n```\n\n## Usage\n```go\nfunc Double(n int) int {\n    return n * 2\n}\n\nf := LogDecorate(Double)\n\nf(5)\n// Starting execution with the integer 5\n// Execution is completed with the result 10\n```\n\n## Rules of Thumb\n- Unlike Adapter pattern, the object to be decorated is obtained by **injection**.\n- Decorators should not alter the interface of an object.\n"
  },
  {
    "path": "structural/proxy/main.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n)\n\n// For example:\n// we must a execute some command\n// so before that we must to create new terminal session\n// and provide our user name and command\nfunc main() {\n\t// Create new instance of Proxy terminal\n\tt, err := NewTerminal(\"gopher\")\n\tif err != nil {\n\t\t// panic: User cant be empty\n\t\t// Or\n\t\t// panic: You (badUser) are not allowed to use terminal and execute commands\n\t\tpanic(err.Error())\n\t}\n\n\t// Execute user command\n\texcResp, excErr := t.Execute(\"say_hi\") // Proxy prints to STDOUT -> PROXY: Intercepted execution of user (gopher), asked command (say_hi)\n\tif excErr != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", excErr.Error()) // Prints: ERROR: I know only how to execute commands: say_hi, man\n\t}\n\n\t// Show execution response\n\tfmt.Println(excResp) // Prints: gopher@go_term$: Hi gopher\n}\n\n/*\n\tFrom that it's can be different terminals realizations with different methods, propertys, yda yda...\n*/\n\n// ITerminal is interface, it's a public method whose implemented in Terminal(Proxy) and Gopher Terminal\ntype ITerminal interface {\n\tExecute(cmd string) (resp string, err error)\n}\n\n// GopherTerminal for example:\n// Its a \"huge\" structure with different public methods\ntype GopherTerminal struct {\n\t// user is a current authorized user\n\tUser string\n}\n\n// Execute just runs known commands for current authorized user\nfunc (gt *GopherTerminal) Execute(cmd string) (resp string, err error) {\n\t// Set \"terminal\" prefix for output\n\tprefix := fmt.Sprintf(\"%s@go_term$:\", gt.User)\n\n\t// Execute some asked commands if we know them\n\tswitch cmd {\n\tcase \"say_hi\":\n\t\tresp = fmt.Sprintf(\"%s Hi %s\", prefix, gt.User)\n\tcase \"man\":\n\t\tresp = fmt.Sprintf(\"%s Visit 'https://golang.org/doc/' for Golang documentation\", prefix)\n\tdefault:\n\t\terr = fmt.Errorf(\"%s Unknown command\", prefix)\n\t}\n\n\treturn\n}\n\n/*\n\tAnd now we will create owr proxy to deliver user and commands to specific objects\n*/\n\n// Terminal is a implementation of Proxy, it's  validates and sends data to GopherTerminal\n// As example before send commands, user must be authorized\ntype Terminal struct {\n\tcurrentUser    string\n\tgopherTerminal *GopherTerminal\n}\n\n// NewTerminal creates new instance of terminal\nfunc NewTerminal(user string) (t *Terminal, err error) {\n\t// Check user if given correctly\n\tif user == \"\" {\n\t\terr = fmt.Errorf(\"User cant be empty\")\n\t\treturn\n\t}\n\n\t// Before we execute user commands, we validate current user, if he have rights to do it\n\tif authErr := authorizeUser(user); authErr != nil {\n\t\terr = fmt.Errorf(\"You (%s) are not allowed to use terminal and execute commands\", user)\n\t\treturn\n\t}\n\n\t// Create new instance of terminal and set valid user\n\tt = &Terminal{currentUser: user}\n\n\treturn\n}\n\n// Execute intercepts execution of command, implements authorizing user, validates it and\n// poxing command to real terminal (gopherTerminal) method\nfunc (t *Terminal) Execute(command string) (resp string, err error) {\n\t// If user allowed to execute send commands then, for example we can decide which terminal can be used, remote or local etc..\n\t// but for example we just creating new instance of terminal,\n\t// set current user and send user command to execution in terminal\n\tt.gopherTerminal = &GopherTerminal{User: t.currentUser}\n\n\t// For example our proxy can log or output intercepted execution... etc\n\tfmt.Printf(\"PROXY: Intercepted execution of user (%s), asked command (%s)\\n\", t.currentUser, command)\n\n\t// Transfer data to original object and execute command\n\tif resp, err = t.gopherTerminal.Execute(command); err != nil {\n\t\terr = fmt.Errorf(\"I know only how to execute commands: say_hi, man\")\n\t\treturn\n\t}\n\n\treturn\n}\n\n// authorize validates user right to execute commands\nfunc authorizeUser(user string) (err error) {\n\t// As we use terminal like proxy, then\n\t// we will intercept user name to validate if it's allowed to execute commands\n\tif user != \"gopher\" {\n\t\t// Do some logs, notifications etc...\n\t\terr = fmt.Errorf(\"User %s in black list\", user)\n\t\treturn\n\t}\n\n\treturn\n}\n"
  },
  {
    "path": "structural/proxy.md",
    "content": "# Proxy Pattern\n\nThe [proxy pattern](https://en.wikipedia.org/wiki/Proxy_pattern) provides an object that controls access to another object, intercepting all calls.\n\n## Implementation\n\nThe proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.\n\nShort idea of implementation:\n```go\n    // To use proxy and to object they must implement same methods\n    type IObject interface {\n        ObjDo(action string)\n    }\n\n    // Object represents real objects which proxy will delegate data\n    type Object struct {\n        action string\n    }\n\n    // ObjDo implements IObject interface and handel's all logic\n    func (obj *Object) ObjDo(action string) {\n        // Action behavior\n        fmt.Printf(\"I can, %s\", action)\n    }\n\n    // ProxyObject represents proxy object with intercepts actions\n    type ProxyObject struct {\n        object *Object\n    }\n\n    // ObjDo are implemented IObject and intercept action before send in real Object\n    func (p *ProxyObject) ObjDo(action string) {\n        if p.object == nil {\n            p.object = new(Object)\n        }\n        if action == \"Run\" {\n            p.object.ObjDo(action) // Prints: I can, Run\n        }\n    }\n```\n\n## Usage\nMore complex usage of proxy as example: User creates \"Terminal\" authorizes and PROXY send execution command to real Terminal object\nSee [proxy/main.go](proxy/main.go) or [view in the Playground](https://play.golang.org/p/mnjKCMaOVE).\n"
  },
  {
    "path": "synchronization/semaphore.md",
    "content": "# Semaphore Pattern\nA semaphore is a synchronization pattern/primitive that imposes mutual exclusion on a limited number of resources. \n\n## Implementation\n\n```go\npackage semaphore\n\nvar (\n\tErrNoTickets      = errors.New(\"semaphore: could not aquire semaphore\")\n\tErrIllegalRelease = errors.New(\"semaphore: can't release the semaphore without acquiring it first\")\n)\n\n// Interface contains the behavior of a semaphore that can be acquired and/or released.\ntype Interface interface {\n\tAcquire() error\n\tRelease() error\n}\n\ntype implementation struct {\n\tsem     chan struct{}\n\ttimeout time.Duration\n}\n\nfunc (s *implementation) Acquire() error {\n\tselect {\n\tcase s.sem <- struct{}{}:\n\t\treturn nil\n\tcase <-time.After(s.timeout):\n\t\treturn ErrNoTickets\n\t}\n}\n\nfunc (s *implementation) Release() error {\n\tselect {\n\tcase _ = <-s.sem:\n\t\treturn nil\n\tcase <-time.After(s.timeout):\n\t\treturn ErrIllegalRelease\n\t}\n\n\treturn nil\n}\n\nfunc New(tickets int, timeout time.Duration) Interface {\n\treturn &implementation{\n\t\tsem:     make(chan struct{}, tickets),\n\t\ttimeout: timeout,\n\t}\n}\n```\n\n## Usage\n### Semaphore with Timeouts\n\n```go\ntickets, timeout := 1, 3*time.Second\ns := semaphore.New(tickets, timeout)\n\nif err := s.Acquire(); err != nil {\n    panic(err)\n}\n\n// Do important work\n\nif err := s.Release(); err != nil {\n    panic(err)\n}\n```\n### Semaphore without Timeouts (Non-Blocking)\n\n```go\ntickets, timeout := 0, 0\ns := semaphore.New(tickets, timeout)\n\nif err := s.Acquire(); err != nil {\n    if err != semaphore.ErrNoTickets {\n        panic(err)\n    }\n\n    // No tickets left, can't work :(\n    os.Exit(1)\n}\n```\n"
  }
]