Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 避免返回接口的设计模式_Go_Design Patterns - Fatal编程技术网

Go 避免返回接口的设计模式

Go 避免返回接口的设计模式,go,design-patterns,Go,Design Patterns,我的应用程序有以下我特意简化的模型,我认为在我使用接口的方式中有很多代码味道: type Library interface { ListCollections(prefix string) []Collection GetItemLocation(item Item) string } type Collection interface { SearchItems(query string) []Item } type Item interface {

我的应用程序有以下我特意简化的模型,我认为在我使用接口的方式中有很多代码味道:

type Library interface {
    ListCollections(prefix string) []Collection
    GetItemLocation(item Item) string    
}
type Collection interface {
    SearchItems(query string) []Item
}
type Item interface {
    Name() string
    Summary() string
}
  • 图书馆有藏书
  • 收藏有物品
  • 库知道项目所在的位置
  • 假设我有十个库(它们将在单独的包中实现,每个包都有其特定性)

    我想操纵处理程序中的库来服务请求。因此,我定义了以下接口:

    type Library interface {
        ListCollections(prefix string) []Collection
        GetItemLocation(item Item) string    
    }
    type Collection interface {
        SearchItems(query string) []Item
    }
    type Item interface {
        Name() string
        Summary() string
    }
    
    我无法定义
    结构,因为每个结构都不同。然而,对于外部世界,拥有
    接口就足够了

    如您所见,我有返回接口的方法,但我并不喜欢它。此外,在本例中,我很难处理
    GetItemLocation
    部分:它需要一个项,但我需要访问该项的字段(特定于每个集合),因此它强制我在方法内键入cast参数


    我可以使用哪些模式来分解这种复杂性并编写更多的diomatic go代码?

    必须在
    GetItemLocation()
    中使用类型断言对我来说似乎不是一个阻碍。也可以考虑不要期望<代码>项目>代码>而只是项目的ID(或者用于标识它的任何东西)。断言的唯一问题是将应该编译时类型的安全性转换为运行时错误。