Book Image

Go Design Patterns

By : Mario Castro Contreras
Book Image

Go Design Patterns

By: Mario Castro Contreras

Overview of this book

Go is a multi-paradigm programming language that has built-in facilities to create concurrent applications. Design patterns allow developers to efficiently address common problems faced during developing applications. Go Design Patterns will provide readers with a reference point to software design patterns and CSP concurrency design patterns to help them build applications in a more idiomatic, robust, and convenient way in Go. The book starts with a brief introduction to Go programming essentials and quickly moves on to explain the idea behind the creation of design patterns and how they appeared in the 90’s as a common "language" between developers to solve common tasks in object-oriented programming languages. You will then learn how to apply the 23 Gang of Four (GoF) design patterns in Go and also learn about CSP concurrency patterns, the "killer feature" in Go that has helped Google develop software to maintain thousands of servers. With all of this the book will enable you to understand and apply design patterns in an idiomatic way that will produce concise, readable, and maintainable software.
Table of Contents (17 chapters)
Go Design Patterns
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Preface

Welcome to the book Go Design Patterns! With this book, you'll learn basic and advanced techniques and patterns with the Go language. Don't worry if you have never written Go code before; this book will gradually introduce you to the various concepts in Go programming. At the same time, experts will find many tips and tricks on the language, so I encourage you to not miss any chapter. If you already know the classic design patterns, you'll find this book very handy, not only as a reference book but also as a way to learn idiomatic Go approaches to solve common problems that you may already know.

The book is divided in three sections:

  • Introduction to the Go language: This is the first part of the book, where you'll learn the basic syntax, the tools that comes with the binary distributions, basic testing, JSON parsing, and more. We leave concurrency for a later chapter to focus on the way that the syntax and the compiler work in a typical Go app.

  • Classic design patterns in idiomatic Go: The second section presents the classic design patterns but as we will see, they are quite different, partly because of the lack of inheritance in Go, but also because we have different and more optimal ways to solve the same problems. A newcomer to the language will find the examples in this section very useful as a way to understand the roots of Go and the idiomatic ways in which you can solve problems using Go in the same manner as you would solve in languages such as Java or C++. Most examples are presented by using TDD and some of them even show examples within Go standard library that uses these patterns.

  • Concurrency patterns: The focus in this section is learning about concurrent structures and parallel execution. You will learn most of the primitives in Go to write concurrent apps, and we will develop some of the classical design patterns with concurrent structures to maximize parallelism. Also, we will learn some of the typical structures to develop concurrent apps in Go. You learn how a classical pattern can become more complex if we need it to work in a concurrent way but the idea is to understand Go concurrent primitives so that the reader finishes the book knowing how to write their own concurrent design patterns by using the knowledge taken from the book.

The book will slowly raise the difficulty of some tasks. We have explained tips and tricks in every chapter.

What this book covers

Chapter 1 , Ready… Steady…Go!, attempts to help newcomers to the Go programming language who have some background in any other programming language. It will begin by showing how to install the Go environment in a Linux machine, moving to syntax, type and flow control.

Chapter 2 , Creational Patterns - Singleton, Builder, Factory, Prototype, and Abstract Factory Design Patterns, introduces the problems that can arise when an object creation or management is particularly complex or expensive using the Singleton, Builder, Factory, and Abstract Factory design patterns.

Chapter 3 , Structural Patterns - Composite, Adapter, and Bridge Design Patterns, deals with the first set of Structural patterns about object composition to get some new functionality. Such as creating an intermediate object and using of various objects as if there is only one.

Chapter 4 , Structural Patterns - Proxy, Facade, Decorator, and Flyweight Design Patterns, is less oriented to multi-object composition but focuses more on obtaining new functionality in existing objects. The Decorator pattern is commonly used to follow the open-closed principle. Facade is extensively used in API’s where you want a single source for many sources of information and actions. Flyweight is not so common but it’s a very useful pattern when the memory is becoming a problem caused by a large collection of similar objects. Finally, the Proxy pattern wraps on an object to provide the same functionality, but at the same time, adding something to the proxy’s functionality.

Chapter 5 ,  Behavioral patterns - Strategy, Chain of Responsibility, Command, and Mediator Design Patterns, deals with the first behavioral pattern to make objects react in an expected or bounded way. We’ll start with the Strategy pattern, perhaps the most important design pattern in object-oriented programming, as many design patterns have something in common with it. Then we’ll move to the Chain of Responsibility to build chains of objects that can decide which between them must deal with a particular case. Finally, Command pattern to encapsulate actions that don’t necessarily need to be executed immediately or must be stored.

Chapter 6 , Behavioral Patterns - Template, Memento, and Interpreter Design Patterns, continues with Behavioral patterns introducing the Interpreter pattern, a quite complex pattern to create small languages and Interpreters for them. It can be very useful when a problem can be solved by inventing a small language for it. The Memento pattern is in front of our eyes every day with the Undo button in apps. The Template pattern helps developers by defining an initial structure of an operation so that the final users of the code can finish it.

Chapter 7 , Behavioral Patterns - Visitor, State, Mediator, and Observer Design Patterns, depicts the Observer pattern, an important pattern that is becoming tremendously popular in distributed systems and reactive programming. The Visitor pattern deals with complex hierarchies of objects where you need to apply a particular action depending on the object. Finally, the State pattern is commonly used in video games and finite state machines and allows an object to change its behavior depending on its own state.

Chapter 8 , Introduction to Go's Concurrency, explains with more detail the CSP concurrency model used in Go by going through some examples using Goroutines and channels, as well as mutexes and syncs.

Chapter 9 , Concurrency Patterns - Barrier, Future, and Pipeline Design Patterns, will introduce some of the CSP concurrency patterns that are idiomatic to the Go language by walking through some examples and explanations. These are small but really powerful patterns so we will provides a few examples of the use of each of them, as well as some schemas (if possible) that will make the understanding of each of them easier.

Chapter 10 ,  Concurrency Patterns -  Workers Pool, and Publish or Subscriber Design Patterns, talks about a couple of patterns with concurrent structures. We will explain every step in detail so you can follow the examples carefully. The idea is to learn patterns to design concurrent applications in idiomatic Go. We are using channels and Goroutines heavily, instead of locks or sharing variables.

What you need for this book

Most of the chapters in this book are written following a simple TDD approach, here the requirements are written first, followed by some unit tests and finally the code that satisfies those requirements. We will use only tools that comes with the standard library of Go as a way to better understand the language and its possibilities. This idea is key to follow the book and understanding the way that Go solves problems, especially in distributed systems and concurrent applications.

Who this book is for

This book is for both beginners and advanced-level developers in the Go programming language. No knowledge of design patterns is expected.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "we need a main function to use it as libraries cannot be converted to executable files directly."

A block of code is set as follows:

    package main

    func main() {
      ten := 10
      if ten == 20 {
        println("This shouldn't be printed as 10 isn't equal to 20")
      } else {
        println("Ten is not equals to 20")
      }
    }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    if "a" == "b" || 10 == 10 || true == false {
      println("10 is equal to 10")
    } else if 11 == 11 && "go" == "go" {
        println("This won't because previous condition was satisfied")
      }
    }

Any command-line input or output is written as follows:

$ go run main.go

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In order to download new modules, we will go to FilesSettings | Project Name | Project Interpreter."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Go-Design-Patterns. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.