Nouveau : Datasets open source gratuits disponibles !Decouvrir →
🐹
langages 20 entrees

Design Patterns en Go

Découvrez les Design Patterns essentiels en Go : Singleton, Observer, Factory.

Voici une cheatsheet exhaustive en français pour Go :

Patterns créationnels

Singleton

type singleton struct {
    data string
}

var instance *singleton

func GetInstance() *singleton {
    if instance == nil {
        instance = &singleton{data: "Unique Instance"}
    }
    return instance
}

Utiliser un seul point d'accès à une ressource unique.

Factory Method

type Shape interface {
    Draw()
}

type Circle struct{}

func (c *Circle) Draw() {
    fmt.Println("Drawing a circle")
}

type Square struct{}

func (s *Square) Draw() {
    fmt.Println("Drawing a square")
}

type ShapeFactory struct{}

func (sf *ShapeFactory) CreateShape(shapeType string) Shape {
    if shapeType == "circle" {
        return &Circle{}
    } else if shapeType == "square" {
        return &Square{}
    }
    return nil
}

Permet de créer des objets sans spécifier la classe exacte.

Patterns structurels

Adapter

type Target interface {
    Request() string
}

type Adaptee struct{}

func (a *Adaptee) SpecificRequest() string {
    return "Specific request"
}

type Adapter struct {
    adaptee *Adaptee
}

func (a *Adapter) Request() string {
    result := a.adaptee.SpecificRequest()
    return fmt.Sprintf("Adapter: %s", result)
}

Permet d'utiliser une interface incompatible avec une autre.

Decorator

type Component interface {
    Operation() string
}

type ConcreteComponent struct{}

func (c *ConcreteComponent) Operation() string {
    return "Operation of ConcreteComponent"
}

type Decorator struct {
    component Component
}

func (d *Decorator) Operation() string {
    return fmt.Sprintf("Decorator: %s", d.component.Operation())
}

Ajouter des responsabilités à un objet dynamiquement.

Patterns comportementaux

Observer

type Subject interface {
    RegisterObserver(o Observer)
    RemoveObserver(o Observer)
    NotifyObservers(data string)
}

type ConcreteSubject struct {
    observers []Observer
    data      string
}

func (s *ConcreteSubject) RegisterObserver(o Observer) {
    s.observers = append(s.observers, o)
}

func (s *ConcreteSubject) RemoveObserver(o Observer) {
    for i, obs := range s.observers {
        if obs == o {
            s.observers = append(s.observers[:i], s.observers[i+1:]...)
            break
        }
    }
}

func (s *ConcreteSubject) NotifyObservers(data string) {
    s.data = data
    for _, o := range s.observers {
        o.Update(s.data)
    }
}

type Observer interface {
    Update(data string)
}

type ConcreteObserver struct{}

func (o *ConcreteObserver) Update(data string) {
    fmt.Println("Received data:", data)
}

Permet à un objet de notifiez d'autres objets lorsque sa state change.

Strategy

type PaymentStrategy interface {
    Pay(amount float64)
}

type CreditCardPayment struct{}

func (c *CreditCardPayment) Pay(amount float64) {
    fmt.Printf("Paid %.2f with credit card\n", amount)
}

type PayPalPayment struct{}

func (p *PayPalPayment) Pay(amount float64) {
    fmt.Printf("Paid %.2f with PayPal\n", amount)
}

type ShoppingCart struct {
    paymentStrategy PaymentStrategy
}

func (c *ShoppingCart) SetPaymentStrategy(paymentStrategy PaymentStrategy) {
    c.paymentStrategy = paymentStrategy
}

func (c *ShoppingCart) Checkout(amount float64) {
    c.paymentStrategy.Pay(amount)
}

Permet de définir une famille d'algorithmes et les rendre interchangeables.

Command

type Command interface {
    Execute()
}

type Light struct{}

func (l *Light) On() {
    fmt.Println("Light is on")
}

func (l *Light) Off() {
    fmt.Println("Light is off")
}

type LightOnCommand struct {
    light *Light
}

func (loc *LightOnCommand) Execute() {
    loc.light.On()
}

type RemoteControl struct {
    command Command
}

func (rc *RemoteControl) SetCommand(command Command) {
    rc.command = command
}

func (rc *RemoteControl) PressButton() {
    rc.command.Execute()
}

Permet d'isoler le lancement d'une demande de commande, sa requête et son action.

Ceci est une cheatsheet complète pour Go, couvrant les principaux patterns de conception. N'hésitez pas à la compléter ou à me demander des explications supplémentaires sur certains concepts.

Projet Go a lancer ?

Besoin d'aide sur un projet ? Decrivez-le pour des conseils personnalises.

Recevoir des conseils

Questions frequentes

A quoi sert cette cheatsheet Go ?
Cette cheatsheet Go regroupe la syntaxe, les commandes et les astuces essentielles pour Go. Elle est concue pour servir d'aide-memoire rapide, que vous soyez debutant ou developpeur confirme cherchant une reference rapide.
Comment utiliser cette cheatsheet Go ?
Parcourez les sections pour trouver la syntaxe ou la commande dont vous avez besoin. Vous pouvez la garder ouverte dans un onglet pendant que vous codez, ou la copier dans vos notes pour un acces hors ligne.
Cette cheatsheet est-elle a jour ?
Oui, nos cheatsheets sont regulierement mises a jour pour refleter les dernieres versions et bonnes pratiques de Go. Si vous remarquez une information obsolete, n'hesitez pas a nous contacter.

Pages liees

Chaque semaine, le meilleur de la tech francaise

Tendances, salaires, outils et opportunites — directement dans votre boite mail.

Gratuit. Desabonnement en un clic. Pas de spam.