Table of Contents
My Go language learning journey and GoFr framework
1. Singleton mode (Creative mode)
2. Adapter pattern (structural pattern)
3. Observer pattern (behavioral pattern)
Option Mode
1. Functional options
2. Builder pattern for options
Master design patterns
Suggested Projects
Home Backend Development Golang Design Patterns in Golang: A Comprehensive Guide

Design Patterns in Golang: A Comprehensive Guide

Jan 20, 2025 pm 10:12 PM

Design Patterns in Golang: A Comprehensive Guide

Go language is favored by developers due to its simplicity and efficiency. Using design patterns in Go projects can significantly improve the scalability and maintainability of applications. This article will explore several common Go language design patterns, with code examples and practical application scenarios.


My Go language learning journey and GoFr framework

As a senior computer science and engineering major, my Go language learning journey began by contributing code to the GoFr framework - an open source framework for building efficient web applications. . It was an exciting challenge, learning a new language while participating in real-world development and learning best practices.

The GoFr framework exposed me to some design patterns and best practices in the Go language, and these experiences shaped the way I write concise, scalable code. In this article, I'm excited to share these insights with you because they have greatly improved my development skills.


1. Singleton mode (Creative mode)

The singleton pattern ensures that a class has only one instance and provides a global access point. This is useful for managing shared resources such as configurations or database connections.

Example:

package main

import (
    "fmt"
    "sync"
)

type Singleton struct{}

var (
    instance *Singleton
    once     sync.Once
)

func GetInstance() *Singleton {
    once.Do(func() {
        instance = &Singleton{}
    })
    return instance
}

func main() {
    obj1 := GetInstance()
    obj2 := GetInstance()
    fmt.Println(obj1 == obj2) // true
}
Copy after login

2. Adapter pattern (structural pattern)

The Adapter pattern acts as a bridge between two incompatible interfaces. This pattern allows you to use existing classes with different interfaces.

Example:

package main

import "fmt"

type LegacyPrinter struct{}

func (l *LegacyPrinter) Print(s string) {
    fmt.Println("Legacy printer output:", s)
}

type ModernPrinter interface {
    PrintMessage(s string)
}

type PrinterAdapter struct {
    legacyPrinter *LegacyPrinter
}

func (p *PrinterAdapter) PrintMessage(s string) {
    p.legacyPrinter.Print(s)
}

func main() {
    legacy := &LegacyPrinter{}
    adapter := &PrinterAdapter{legacyPrinter: legacy}
    adapter.PrintMessage("Hello from adapter!")
}
Copy after login

3. Observer pattern (behavioral pattern)

The observer pattern defines a dependency relationship between objects, so that when an object changes state, all objects that depend on it will be notified.

Example:

package main

import "fmt"

type Observer interface {
    Update(string)
}

type Subject struct {
    observers []Observer
}

func (s *Subject) Attach(o Observer) {
    s.observers = append(s.observers, o)
}

func (s *Subject) Notify(msg string) {
    for _, o := range s.observers {
        o.Update(msg)
    }
}

type ConcreteObserver struct {
    name string
}

func (c *ConcreteObserver) Update(msg string) {
    fmt.Printf("%s received message: %s\n", c.name, msg)
}

func main() {
    subject := &Subject{}
    observer1 := &ConcreteObserver{name: "Observer1"}
    observer2 := &ConcreteObserver{name: "Observer2"}

    subject.Attach(observer1)
    subject.Attach(observer2)

    subject.Notify("Hello, Observers!")
}
Copy after login

Option Mode

Option mode is a flexible way to configure Go language structures, which can write simpler and easier to maintain code. There are two common methods:

1. Functional options

The functional option uses functions to modify the properties of the structure.

Example:

package main

import "fmt"

type Server struct {
    Host string
    Port int
}

func NewServer(opts ...func(*Server)) *Server {
    server := &Server{
        Host: "localhost",
        Port: 8080,
    }

    for _, opt := range opts {
        opt(server)
    }

    return server
}

func WithHost(host string) func(*Server) {
    return func(s *Server) {
        s.Host = host
    }
}

func WithPort(port int) func(*Server) {
    return func(s *Server) {
        s.Port = port
    }
}

func main() {
    server := NewServer(WithHost("127.0.0.1"), WithPort(9090))
    fmt.Printf("Server: %+v\n", server)
}
Copy after login

2. Builder pattern for options

The builder pattern can also be used to configure a structure with multiple optional parameters.

Example:

package main

import "fmt"

type Server struct {
    Host string
    Port int
}

type ServerBuilder struct {
    server Server
}

func (b *ServerBuilder) SetHost(host string) *ServerBuilder {
    b.server.Host = host
    return b
}

func (b *ServerBuilder) SetPort(port int) *ServerBuilder {
    b.server.Port = port
    return b
}

func (b *ServerBuilder) Build() Server {
    return b.server
}

func main() {
    builder := &ServerBuilder{}
    server := builder.SetHost("127.0.0.1").SetPort(9090).Build()
    fmt.Printf("Server: %+v\n", server)
}
Copy after login

Master design patterns

The best way to improve your ability to master design patterns is through practical application. Weekend projects and participation in open source projects can accelerate learning. One of the projects I can participate in is GoFr, where I have the opportunity to improve my Go language skills by working on real-world problems.

Design Patterns in Golang: A Comprehensive Guide

Suggested Projects

  • GoFr: GitHub repository
  • Build simple REST APIs using different patterns.
  • Create a library that implements various design patterns in the Go language.

By practicing on these projects, you will gain practical experience and a deeper understanding of how design patterns solve real-world problems.

The above is the detailed content of Design Patterns in Golang: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

See all articles