golang 设计模式
时间: 2024-01-04 22:20:37 浏览: 143
以下是几种常见的Golang设计模式:
1. 工厂模式(Factory Pattern):用于创建对象的模式,通过定义一个创建对象的接口来实现对象的实例化。
```go
type Shape interface {
Draw()
}
type Circle struct{}
func (c *Circle) Draw() {
fmt.Println("Drawing a circle")
}
type Rectangle struct{}
func (r *Rectangle) Draw() {
fmt.Println("Drawing a rectangle")
}
type ShapeFactory struct{}
func (sf *ShapeFactory) GetShape(shapeType string) Shape {
if shapeType == "circle" {
return &Circle{}
} else if shapeType == "rectangle" {
return &Rectangle{}
}
return nil
}
func main() {
factory := &ShapeFactory{}
circle := factory.GetShape("circle")
circle.Draw() // 输出:Drawing a circle
rectangle := factory.GetShape("rectangle")
rectangle.Draw() // 输出:Drawing a rectangle
}
```
2. 单例模式(Singleton Pattern):确保一个类只有一个实例,并提供一个全局访问点。
```go
type Singleton struct{}
var instance *Singleton
func GetInstance() *Singleton {
if instance == nil {
instance = &Singleton{}
}
return instance
}
func main() {
singleton1 := GetInstance()
singleton2 := GetInstance()
fmt.Println(singleton1 == singleton2) // 输出:true
}
```
3. 观察者模式(Observer Pattern):定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。
```go
type Subject struct {
observers []Observer
}
func (s *Subject) Attach(observer Observer) {
s.observers = append(s.observers, observer)
}
func (s *Subject) Notify() {
for _, observer := range s.observers {
observer.Update()
}
}
type Observer interface {
Update()
}
type ConcreteObserver struct{}
func (co *ConcreteObserver) Update() {
fmt.Println("Observer is updated")
}
func main() {
subject := &Subject{}
observer := &ConcreteObserver{}
subject.Attach(observer)
subject.Notify() // 输出:Observer is updated
}
```
阅读全文