在Go语言中,工厂函数(Factory Function)是一种常见的设计模式,用于创建特定类型的对象实例。工厂函数在创建对象时提供了更好的封装和控制,可以隐藏对象的创建细节,同时也能够返回特定类型或接口的实例。
使用工厂函数创建不同类型的几何形状。
package main
import (
"fmt"
"math"
)
// Shape 接口定义了几何形状的方法
type Shape interface {
Area() float64
Perimeter() float64
}
// Circle 表示圆形
type Circle struct {
Radius float64
}
// Rectangle 表示矩形
type Rectangle struct {
Width float64
Height float64
}
// 工厂函数创建圆形实例
func NewCircle(radius float64) *Circle {
return &Circle{Radius: radius}
}
// 实现 Shape 接口的 Area 方法
func (c *Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
// 实现 Shape 接口的 Perimeter 方法
func (c *Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}
// 工厂函数创建矩形实例
func NewRectangle(width, height float64) *Rectangle {
return &Rectangle{Width: width, Height: height}
}
// 实现 Shape 接口的 Area 方法
func (r *Rectangle) Area() float64 {
return r.Width * r.Height
}
// 实现 Shape 接口的 Perimeter 方法
func (r *Rectangle) Perimeter() float64 {
return 2*r.Width + 2*r.Height
}
func main() {
circle := NewCircle(5)
rectangle := NewRectangle(3, 4)
shapes := []Shape{circle, rectangle}
for _, shape := range shapes {
fmt.Printf("Type: %T, Area: %f, Perimeter: %f\n", shape, shape.Area(), shape.Perimeter())
}
}
在这个示例中,我们定义了一个 Shape
接口,然后实现了 Circle
和 Rectangle
结构体,分别表示圆形和矩形。通过 NewCircle
和 NewRectangle
工厂函数,我们可以创建不同类型的几何形状。使用工厂函数,我们可以隐藏对象的构造细节,并返回实现了 Shape
接口的具体对象。最后,我们将不同的几何形状放入一个切片中,并通过循环遍历来计算它们的面积和周长。
这个示例演示了如何使用工厂函数来创建对象,将对象的创建和使用分离开来,提高了代码的可读性和灵活性。