登录
首页 >  Golang >  Go问答

Golang 中的工厂函数

来源:stackoverflow

时间:2024-03-19 22:06:36 301浏览 收藏

在 Go 语言中,工厂函数是一种设计模式,用于创建对象。当您需要基于不同条件创建不同类型的对象时,可以使用工厂函数。本文讨论了在 ComputeService 中使用工厂函数来实现速率限制的两种方法。第一种方法是为每个请求创建新的 ComputeService 对象,并根据处理程序中的用户类型解析速率限制器。第二种方法是在启动时初始化 ComputeService 对象,并通过调用提供程序函数在每次 Compute() 调用中解析速率限制器。

问题内容

我有一个类似于下面所示的服务对象,它通过 http 公开:

type computeservice struct {

}

func (svc computeservice) compute(usertype string, data data) (result, error) {
   // rate limit based on usertype (both check and increment counter)
   // if not rate limited, compute and return result
}

现在,如您所见,需要基于 usertype 进行速率限制。速率限制器本身的实现根据 usertype 进行更改。我正在考虑使用 usertype 解决速率限制器的两种方法。

// First approach: for each request new ComputeService object is
// created after resolving RateLimiter using userType in the handler
// itself
type ComputeService struct {
    RateLimiter RateLimiter
}

// Second approach: ComputeService object is initialized during startup
// and only RateLimiter is resolved with every Compute() call by calling
// the provider function
type ComputeService struct {
    RateLimiterProvider func(userType string) RateLimiter
}

两者都是可测试的。哪一个更可取?我倾向于第二种方法,因为使用它意味着处理程序将纯粹是读取请求、委托给服务、写出响应,而在第一种方法中,处理程序将包含解决速率限制器实现的额外步骤。


解决方案


如果您使用像 Dargo 这样的 di 系统,您可以使用其 provider 注入在运行时动态选择实现。

在这种情况下,您的服务将如下所示:

import "github.com/jwells131313/dargo/ioc"

type ratelimiter interface {
}

type usertype1ratelimiter struct {
}

type usertype2ratelimiter struct {
}

type computeservice struct {
    ratelimiterprovider ioc.provider `inject:"ratelimiter"`
}

func (svc computeservice) compute(usertype string, data data) (result, error) {
    // rate limit based on usertype (both check and increment counter)
    // if not rate limited, compute and return result
    raw, err := svc.ratelimiterprovider.qualifiedby(usertype).get()
    if err != nil {
        return nil, err
    }

    limiter := raw.(ratelimiter)
    //...
}

这是将它们绑定到 servicelocator 中的方法:

func initializer() {
    serviceLocator, _ = ioc.CreateAndBind("ExampleLocator", func(binder ioc.Binder) error {
        binder.Bind("RateLimiter", UserType1RateLimiter{}).QualifiedBy("UserType1")
        binder.Bind("RateLimiter", UserType2RateLimiter{}).QualifiedBy("UserType2")
        binder.Bind("ComputeService", ComputeService{})
        return nil
    })
}

这仅适用于您使用 dargo 之类的东西时,但它对您的情况仍然可能有用。

如果你不使用 dargo,在我看来这是一个意见问题,尽管我个人会选择第二种方法

理论要掌握,实操不能落!以上关于《Golang 中的工厂函数》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>