一分钟编--golang实现工厂模式

59 阅读1分钟

概述

抽象工厂模式是一种创建型设计模式,它提供了一种封装一组具有共同主题的单独工厂,而无需指定其具体类。在 Golang 中,抽象工厂模式可以帮助我们创建一组相关的对象,而无需关心其具体实现。在 Go 中,我们可以使用接口来定义抽象工厂和具体工厂。

[下面是一个简单的例子,演示如何在 Golang 中编写一个抽象工厂模式。]

package main

import "fmt"

type Shape interface {
    Draw()
}

type Circle struct{}

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

type Rectangle struct{}

func (r *Rectangle) Draw() {
    fmt.Println("Rectangle Draw")
}

type ShapeFactory interface {
    CreateCircle() Shape
    CreateRectangle() Shape
}

type SimpleShapeFactory struct{}

func (s *SimpleShapeFactory) CreateCircle() Shape {
    return &Circle{}
}

func (s *SimpleShapeFactory) CreateRectangle() Shape {
    return &Rectangle{}
}

func main() {
    var factory ShapeFactory
    factory = &SimpleShapeFactory{}

    circle := factory.CreateCircle()
    rectangle := factory.CreateRectangle()

    circle.Draw()
    rectangle.Draw()
}

在这个例子中,我们定义了两个形状:圆形和矩形。我们还定义了一个接口 Shape,它有一个方法 Draw()。然后我们定义了一个抽象工厂接口 ShapeFactory,它有两个方法 CreateCircle() 和 CreateRectangle(),用于创建圆形和矩形。最后,我们实现了一个具体的工厂 SimpleShapeFactory,它实现了 ShapeFactory 接口,并返回 Circle 和 Rectangle 的实例。

如果您想了解更多关于 Golang 抽象工厂模式的内容,请告诉我您感兴趣的方面,我会尽力回答您的问题。