What design patterns do you know and which ones do you apply in your work?
sobes.tech AI
Answer from AI
Some common design patterns and their application in Go:
-
Singleton — ensures that a class has only one instance. In Go, it is often implemented using package variables and
sync.Once. -
Factory — creating objects through factory functions, which is convenient for encapsulating creation logic and selecting specific interface implementations.
-
Decorator — adding functionality to objects dynamically. In Go, it can be implemented through function wrappers or structures implementing the same interface.
-
Strategy — choosing an algorithm at runtime. In Go, it involves passing functions or interfaces with different implementations.
-
Observer — subscribing to events. In Go, it can be implemented using channels and goroutines.
Example of a factory in Go:
package main
type Animal interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string { return "Woof!" }
type Cat struct{}
func (c Cat) Speak() string { return "Meow!" }
func AnimalFactory(animalType string) Animal {
switch animalType {
case "dog":
return Dog{}
case "cat":
return Cat{}
default:
return nil
}
}
func main() {
a := AnimalFactory("dog")
println(a.Speak()) // Woof!
}
In my work, I apply patterns that simplify code maintenance, make it more readable and extendable, such as Factory for creating services, Strategy for selecting algorithms, and Decorator for adding logging or caching.