在Go中实现工厂模式,可以定义一个工厂接口和实现该接口的具体工厂类型。以下是一个简单的例子:
package main
import "fmt"
// 定义一个接口,所有的具体产品都需要实现这个接口
type Product interface {
Use() string
}
// 具体的产品A
type ConcreteProductA struct{}
func (p *ConcreteProductA) Use() string {
return "使用产品A"
}
// 具体的产品B
type ConcreteProductB struct{}
func (p *ConcreteProductB) Use() string {
return "使用产品B"
}
// 工厂接口
type Factory interface {
CreateProduct() Product
}
// 具体的工厂,用来创建产品A
type ConcreteFactoryA struct{}
func (f *ConcreteFactoryA) CreateProduct() Product {
return &ConcreteProductA{}
}
// 具体的工厂,用来创建产品B
type ConcreteFactoryB struct{}
func (f *ConcreteFactoryB) CreateProduct() Product {
return &ConcreteProductB{}
}
func main() {
// 创建工厂A
factoryA := &ConcreteFactoryA{}
// 使用工厂A创建产品
productA := factoryA.CreateProduct()
fmt.Println(productA.Use())
// 创建工厂B
factoryB := &ConcreteFactoryB{}
// 使用工厂B创建产品
productB := factoryB.CreateProduct()
fmt.Println(productB.Use())
}