Giter Club home page Giter Club logo

golang-pattern's Introduction

Go Design Pattern

Creational

Builder

The Builder Pattern isolates an object's construction to increase your codes readability.

The following program creates a notification function in .\Creational\Builder\builder.go that can be called, and provided with the necessary variables, from your main function in .\Creational\Builder\main.go:

Bash:

go run ./Creational/Builder/*.go
Notification: &{title:New Notification subtitle: message:This is a level 3 alert! image:image.jpg icon:icon.png priority:3 notType:alert}

Powershell:

go run .\Creational\Builder\builder.go .\Creational\Builder\notification.go .\Creational\Builder\main.go
Notification: &{title:New Notification subtitle: message:This is a level 3 alert! image:image.jpg icon:icon.png priority:3 notType:alert}

Remove the image or set the priority outside of the range between 1-5 to trigger the error checks:

bldr.SetImage("")
bldr.SetPriority(0)
$ go run ./*.go
Error: You need to provide an image when using an icon!
$ go run ./*.go
Error: Priority has to be between 1 and 5!

Factory

The Factory Pattern allows us to create an object when it's types are not yet determined.

The program allocates the creation of the object to the factory function. The factory then decides, based on the specified type, what creation function to use

go run ./Creational/Factory/*.go

Magazine name: Programmer.Inc
Type: *main.magazine
Name: Programmer.Inc
Pages: 47
Publisher: WTF! kubectl
----------------------

Magazine name: Rust Formation
Type: *main.magazine
Name: Rust Formation
Pages: 46
Publisher: New & Shiny
----------------------

Newspaper name: Vanuatu Daily
Type: *main.newspaper
Name: Vanuatu Daily
Pages: 44
Publisher: Island Life
----------------------

Newspaper name: clickBait
Type: *main.newspaper
Name: clickBait
Pages: 42
Publisher: The Sun
----------------------

Singleton

The Singleton Pattern allows only one instance of a class and provides global access to it.

Basic Example

 go run ./Creational/Singelton/*.go

Creating logger instance
Providing logger instance
1 : Log level 1 message
Providing logger instance
2 : Log level 2 message
Providing logger instance
3 : Log level 3 message

Only one instance is (lazy) created on the first incoming call. The instance is then re-used for the 2 following calls.

Thread-safe Example

When the singleton is called on multiple threads we might end up with several instances - e.g.:

for i := 1; i < 10; i++ {
    getLoggerInstance()
}
fmt.Scanln()

To prevent this create:

var once sync.Once

And wrap your creation with it:

once.Do(func ()  {
    // Lazy create logger on first call
    fmt.Println("Creating logger instance")
    logger = &AppLogger{}	
})
go run ./Creational/Singelton_Thread_Safe/*.go

Creating logger instance
Providing logger instance
Providing logger instance
Providing logger instance
Providing logger instance
Providing logger instance
Providing logger instance
Providing logger instance
Providing logger instance
Providing logger instance

And this makes sure that the creation step only runs once, even if there are concurrent requests coming in.

Structural

Adapter

The Adapter Pattern allows you to use an existing interface of an API as another interface without modifying the original API.

Example use case: adapting legacy code to a new API - e.g. integrating an old media center software into a new environment. The adapter allows us to send the same commands to each device to get the same, desired result:

go run ./Structural/Adapter/*.go

XBMC is On
XBMC Volume: 34
XBMC Volume: 35
XBMC Channel: 98
XBMC Channel: 97
XBMC Channel: 98
XBMC Channel: 1
XBMC is Off
-----------------------
OSMC is On
OSMC Volume is: 11
Setting OSMC Volume to: 10
OSMC Volume is: 10
Setting OSMC Volume to: 11
OSMC channel is: 21
Setting OSMC Channel to: 20
OSMC channel is: 20
Setting OSMC Channel to: 19
OSMC channel is: 19
Setting OSMC Channel to: 20
Setting OSMC Channel to: 21
OSMC is Off

Facade

The Facade Pattern adds a simpler access point to your system hiding a more complex, low-level API.

go run ./Structural/Facade/*.go

Preparing an Americano
----------------------
Order for coffee with 146.875 grams of beans and grind level 6 .
Grinding 146.875 grams of beans at level 6 .
Adding 235 mL of hot water.
Not adding milk foam.
Order processed.
Americano is ready

Preparing a Latte
----------------------
Order for coffee with 131.25 grams of beans and grind level 2 .
Grinding 131.25 grams of beans at level 2 .
Adding 350 mL of hot water.
Adding 87.5 mL of milk.
Adding milk foam.
Order processed.
Latte is ready

Behavioural

Observer

The Observer Pattern introduces a Pub/Sub architecture where an object (Subject) maintains a list of other objects (Observers) that it needs to notify about changes.

go run ./Behavioural/Observer/*.go

Brother Number One was registered
Brother Number Two was registered
Brother Number One received update: Update 1
Brother Number Two received update: Update 1
Brother Number One received update: Update 2
Brother Number Two received update: Update 2
Brother Number One received update: Update 3
Brother Number Two received update: Update 3
Brother Number One was deregistered
Brother Number Two received update: Update 4

Iterator

The Iterator Pattern iterates over the elements inside an object without exposing the underlying implementation of the container

Callback Iteration

The library data is pushed to the callBack and then processed:

go run ./Behavioral/Iterator/Callback/*.go

Book title: Leviathan Wakes
Book title: Caliban's War
Book title: Abaddon's Gate
Book title: Cibola Burn
Book title: Nemesis Games
Book title: Babylon's Ashes
Book title: Persepolis Rising
Book title: Tiamat's Wrath
Book title: Leviathan Falls
Published: 2011
Published: 2012
Published: 2013
Published: 2014
Published: 2015
Published: 2016
Published: 2017
Published: 2019
Published: 2021

Pull Model Iteration

go run ./Behavioral/Iterator/Interface/*.go

Book &{Name:Leviathan Wakes Year:2011 PageCount:592 ISBN:978-0-316-12908-4 Type:0}
Book &{Name:Caliban's War Year:2012 PageCount:595 ISBN:978-1-841-49990-1 Type:1}
Book &{Name:Abaddon's Gate Year:2013 PageCount:539 ISBN:978-0-316-12907-7 Type:0}
Book &{Name:Cibola Burn Year:2014 PageCount:583 ISBN:978-0-316-21762-0 Type:2}
Book &{Name:Nemesis Games Year:2015 PageCount:544 ISBN:978-0-316-21758-3 Type:0}
Book &{Name:Babylon's Ashes Year:2016 PageCount:608 ISBN:978-0-316-33474-7 Type:0}
Book &{Name:Persepolis Rising Year:2017 PageCount:560 ISBN:978-0-316-33283-5 Type:0}
Book &{Name:Tiamat's Wrath Year:2019 PageCount:544 ISBN:978-0-316-33286-6 Type:0}
Book &{Name:Leviathan Falls Year:2021 PageCount:528 ISBN:978-0-356-51039-2 Type:3}

golang-pattern's People

Contributors

mpolinowski avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.