Curated list of Go design patterns, recipes and idioms

Go Patterns
build-status awesome license

A curated collection of idiomatic design & application patterns for Go language.

Creational Patterns

Pattern Description Status
Abstract Factory Provides an interface for creating families of releated objects
Builder Builds a complex object using simple objects
Factory Method Defers instantiation of an object to a specialized function for creating instances
Object Pool Instantiates and maintains a group of objects instances of the same type
Singleton Restricts instantiation of a type to one object

Structural Patterns

Pattern Description Status
Bridge Decouples an interface from its implementation so that the two can vary independently
Composite Encapsulates and provides access to a number of different objects
Decorator Adds behavior to an object, statically or dynamically
Facade Uses one type as an API to a number of others
Flyweight Reuses existing instances of objects with similar/identical state to minimize resource usage
Proxy Provides a surrogate for an object to control it's actions

Behavioral Patterns

Pattern Description Status
Chain of Responsibility Avoids coupling a sender to receiver by giving more than object a chance to handle the request
Command Bundles a command and arguments to call later
Mediator Connects objects and acts as a proxy
Memento Generate an opaque token that can be used to go back to a previous state
Observer Provide a callback for notification of events/changes to data
Registry Keep track of all subclasses of a given class
State Encapsulates varying behavior for the same object based on its internal state
Strategy Enables an algorithm's behavior to be selected at runtime
Template Defines a skeleton class which defers some methods to subclasses
Visitor Separates an algorithm from an object on which it operates

Synchronization Patterns

Pattern Description Status
Condition Variable Provides a mechanism for threads to temporarily give up access in order to wait for some condition
Lock/Mutex Enforces mutual exclusion limit on a resource to gain exclusive access
Monitor Combination of mutex and condition variable patterns
Read-Write Lock Allows parallel read access, but only exclusive access on write operations to a resource
Semaphore Allows controlling access to a common resource

Concurrency Patterns

Pattern Description Status
N-Barrier Prevents a process from proceeding until all N processes reach to the barrier
Bounded Parallelism Completes large number of independent tasks with resource limits
Broadcast Transfers a message to all recipients simultaneously
Coroutines Subroutines that allow suspending and resuming execution at certain locations
Generators Yields a sequence of values one at a time
Reactor Demultiplexes service requests delivered concurrently to a service handler and dispatches them syncronously to the associated request handlers
Parallelism Completes large number of independent tasks
Producer Consumer Separates tasks from task executions

Messaging Patterns

Pattern Description Status
Fan-In Funnels tasks to a work sink (e.g. server)
Fan-Out Distributes tasks among workers (e.g. producer)
Futures & Promises Acts as a place-holder of a result that is initially unknown for synchronization purposes
Publish/Subscribe Passes information to a collection of recipients who subscribed to a topic
Push & Pull Distributes messages to multiple workers, arranged in a pipeline

Stability Patterns

Pattern Description Status
Bulkheads Enforces a principle of failure containment (i.e. prevents cascading failures)
Circuit-Breaker Stops the flow of the requests when requests are likely to fail
Deadline 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)
Fail-Fast Checks the availability of required resources at the start of a request and fails if the requirements are not satisfied
Handshaking Asks a component if it can take any more load, if it can't, the request is declined
Steady-State For every service that accumulates a resource, some other service must recycle that resource

Profiling Patterns

Pattern Description Status
Timing Functions Wraps a function and logs the execution

Idioms

Pattern Description Status
Functional Options Allows creating clean APIs with sane defaults and idiomatic overrides

Anti-Patterns

Pattern Description Status
Cascading Failures A failure in a system of interconnected parts in which the failure of a part causes a domino effect
Comments
  • Add Producer Consumer Part

    Add Producer Consumer Part

    There are three parts changed:

    • Add producer_consumer.md and update the README.md in root dir.

    • Add producer_consumer package:

    We can use assign tasks to producer after producer starts.
    Producer has limit buffer for task. If the buffer is full and no
    consumer to take, the producer will ignore the task.
    Consumer needs to regiester if it wants to do task for producer.
    
    All the communication is based on RPC.
    
    • Add example for producer_consumer package.
    The example will show the case that the buffer of producer is full.
    
  • creational/abstract-factory: implement abstract pattern

    creational/abstract-factory: implement abstract pattern

    Hi Tamer

    It works now :) The problem was that I tried to make an remote branch to compare to master branch. But I had no permission. Then I realized that I can make a fork to compare to the master branch :)

    Hope it is good enough to integrate (still in the learning curve)

    Best regards

    Steve aka Inux

  • Circuit breaker is broken, and was copied without credit

    Circuit breaker is broken, and was copied without credit

  • synchronization/semaphore

    synchronization/semaphore

    Hi! I saw that a some patterns have a link to related implementation (e.g. http://tmrts.com/go-patterns/stability/circuit-breaker.html). Can I add via pull request some implementation of synchronization/semaphore?

    • https://github.com/eapache/go-resiliency/blob/master/semaphore/semaphore.go
    • https://github.com/dropbox/godropbox/blob/master/sync2/semaphore.go
    • https://github.com/kamilsk/semaphore
  • go-patterns/messaging/publish_subscribe.md

    go-patterns/messaging/publish_subscribe.md

  • Functional Options: Create a relative package, set the link

    Functional Options: Create a relative package, set the link

    Hi @tmrts, First of all I don't want this to act like 'advertisement' ( I personally don't like 'advertisements' in github), if it's acted like that then do not approve this PR.

    I made a package only to help readers of this go-patterns repository to understand how they can extend Pattern: Functional Options to fit to their needs, so I added a section with relative links of this particular pattern. I could also recommend search and do the same for other patterns, it's good to add relative links in order to see how they(readers) can extend a pattern, it will help to understand better the subject, I hope.

  • Factory Method Pattern

    Factory Method Pattern

    Factory Method Pattern in Go is function which returns an interface (something what is implementing an interface)... that's all. This means you should not think about this pattern and use a pattern when you known patterns. You should make only a function like func NewXXX(arguments) <interface> {...} for your needs (or in ideal case package.New()). And every gofer are making this everyday. And it is not a pattern. This is Interface builder or Interface constructor as you like. I affirm that Go does not require knowledge of any patterns (as OOP requires), but it requires an understanding of SOLID principles and having a mind.

23 design patterns of GoF

GoF 设计模式 GoF所提出的23种设计模式主要基于以下面向对象设计原则: 对接口编程而不是对实现编程 优先使用对象组合而不是继承 23种设计模式分为三大类:创建型模式(Creational Patterns)、结构型模式(Structural Patterns)、行为型模式(Behavioral

Nov 29, 2022
Go Design Patterns
Go Design Patterns

Creational patterns provide out-of-the-box objects for users instead relying on the user to know how to build the object which in some cases could be complex.

Feb 8, 2022
Cook amazing genetic parts using our cookbook. Recipes and synthetic biology tools to take your breath away.

friendzymes-cookbook Friendly tools for a friendly community. A collection of tutorials and genetic tools for synthetic biology. This cookbook is a su

Aug 19, 2022
Go from the beginning - A book on Go, contains fundamentals but also recipes

Go from the beginning Welcome to Go from the beginning, a free book containing 25+ lessons that will take you from "zero to hero" in the amazing langu

Dec 28, 2022
Concurrency patterns in Go

Concurrency patterns in Go

Dec 28, 2022
Binaryscarf generates double-knitting patterns for some corpus of input text.

binaryscarf binaryscarf generates double-knit patterns for some corpus of input text. The layout follows the same style as described here. Output is s

Dec 31, 2022
Patternfinder - Find patterns in http output based on regex string. Display occurences

Patternfinder Find patterns in HTTP output based on regex string. Display occurr

Feb 18, 2022
Practical concurrency guide in Go, communication by channels, patterns

Go Concurrency Guide This guide is built on top of the some examples of the book Go Concurrency in Go and Go Programming Language Race Condition and D

Dec 28, 2022
Tool (in Go!) to compare and diff container and host environments. Dinosaur fun!

Compe compare environments and other things between containers, and host ??️ This is a simple tool to compare environments and other features of conta

Sep 24, 2022
Go Cheat Sheet - An overview of Go syntax and features.

Go Cheat Sheet - An overview of Go syntax and features.

Dec 31, 2022
An online book focusing on Go syntax/semantics and runtime related things

Go 101 is a book focusing on Go syntax/semantics and all kinds of runtime related things. It tries to help gophers gain a deep and thorough understanding of Go. This book also collects many details of Go and in Go programming. The book is expected to be helpful for both beginner and experienced Go programmers.

Dec 29, 2022
This slide deck and supporting material is part of the Introduction to Go training course by Dave Cheney

This slide deck and supporting material is part of the Introduction to Go training course by Dave Cheney.

Nov 14, 2022
📖 Build a RESTful API on Go: Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers.
📖 Build a RESTful API on Go: Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers.

?? Tutorial: Build a RESTful API on Go Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers. ?? The full article is published on Marc

Dec 27, 2022
Assert your Go code is inlined and bounds-check eliminated

gcassert gcassert is a program for making assertions about compiler decisions in Golang programs, via inline comment directives like //gcassert:inline

Oct 27, 2022
1000+ Hand-Crafted Go Examples, Exercises, and Quizzes

A Huge Number of Go Examples, Exercises and Quizzes Best way of learning is doing. Inside this repository, you will find thousands of Go examples, exe

Jan 1, 2023
Official provider for VMware desktop products: Fusion, Player, and Workstation.

Vagrant VMware Desktop Providers This is the common codebase for the official providers for VMware desktop products: Fusion, Player, and Workstation.

Jan 7, 2023
A complete guide to undersatnd golang programming language, web requests, JSON and creating web APIs with mongodb

Golang series A complete guide to undersatnd golang programming language, web requests, JSON and creating web APIs with mongodb LearnCodeonline.in 01

Jan 1, 2023
Golang Clean Architecture based on Uncle Bob's Clean Architecture and Summer internship in 2021

clean-architecture-api Description This is an example of implemention of Clean Architecture in Golang projects. This project has 4 layer : Infrastruct

Feb 20, 2022
Learning and Practice - Go Lang

Go Lang - Learning and Practice All the code stored here is provided by Tour of Go Basics Packages, variables, and functions Flow control statements:

Jan 14, 2022