go实现工厂模式

在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())
}

相关推荐

  1. go实现工厂模式

    2024-04-08 23:12:04       38 阅读
  2. [go] 抽象工厂模式

    2024-04-08 23:12:04       48 阅读
  3. go设计模式工厂方法模式

    2024-04-08 23:12:04       33 阅读
  4. 工厂模式实现

    2024-04-08 23:12:04       66 阅读
  5. go-factory工厂模式样例

    2024-04-08 23:12:04       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-08 23:12:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-08 23:12:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-08 23:12:04       87 阅读
  4. Python语言-面向对象

    2024-04-08 23:12:04       96 阅读

热门阅读

  1. GO - 泛型编程

    2024-04-08 23:12:04       41 阅读
  2. 面向对象设计之开闭原则

    2024-04-08 23:12:04       41 阅读
  3. ComfyUI是什么?

    2024-04-08 23:12:04       41 阅读
  4. 前端开发语言有哪些?

    2024-04-08 23:12:04       38 阅读
  5. ML Olympiad returns with over 20 challenges

    2024-04-08 23:12:04       41 阅读
  6. 224.0.0.1到224.0.0.9的IP地址

    2024-04-08 23:12:04       38 阅读
  7. 题目 3158: 三国游戏

    2024-04-08 23:12:04       32 阅读
  8. Azure AI 新发布了 9 种更逼真的对话 AI 声音

    2024-04-08 23:12:04       37 阅读