简单工厂模式(Simple Factory Pattern)
简单工厂模式(Simple Factory Pattern)是一种创建型设计模式,它提供了一种简单的方式来创建对象,而不需要暴露对象的创建逻辑。在这个模式中,我们将创建对象的责任交给一个专门的工厂函数。该函数根据参数不同,返回不同的实例对象。
在 Go 语言中,通常使用包函数来实现简单工厂模式。我们将工厂函数定义为包级别的函数,根据传入的参数决定返回哪种类型的实例。以下是一个使用包函数实现简单工厂模式的示例。
假设我们需要创建两种形状:圆形和矩形。首先定义形状接口 Shape
和两个实现了该接口的结构体:Circle
和 Rectangle
。然后定义一个名为 NewShape
的包函数,该函数根据传入的参数返回相应的形状实例。
// Shape 接口
type Shape interface {
Draw() string
}
// Circle 结构体
type Circle struct{}
// Draw 方法实现
func (c *Circle) Draw() string {
return "Circle"
}
// Rectangle 结构体
type Rectangle struct{}
// Draw 方法实现
func (r *Rectangle) Draw() string {
return "Rectangle"
}
// 工厂函数
func NewShape(shapeType string) Shape {
switch shapeType {
case "circle":
return new(Circle)
case "rectangle":
return new(Rectangle)
default:
return nil
}
}
在上面的示例中,我们定义了 Shape
接口和 Circle
和 Rectangle
两个结构体。我们将 NewShape
包函数定义为简单工厂函数,该函数根据传入的参数决定返回哪个结构体的实例。
以下是使用示例代码:
func main() {
circle := NewShape("circle")
rectangle := NewShape("rectangle")
fmt.Println(circle.Draw()) // 输出: Circle
fmt.Println(rectangle.Draw()) // 输出: Rectangle
}
这里我们使用 NewShape
函数分别创建了圆形和矩形的实例,然后分别调用 Draw
方法打印出它们的名称。
希望这个例子能够帮助你更好地理解如何使用包函数实现简单工厂模式。
推荐文章: