我有两个接口(interface)。它们几乎相同,唯一的区别是 Set
方法:
type Cache1 interface {
Set(key, value interface{}, ttl time.Duration) bool
}
type Cache2 interface {
Set(key, value interface{}) bool
}
知道如何将它们统一为一个抽象概念吗?当然,我可以将 ttl time.Duration
添加到第二个接口(interface),但它在那里没有用,并且会降低代码的可读性。如果存在的话,你能建议复杂的模式吗?
最佳答案
我想,在合并这些方法时你应该注意接口(interface)隔离原则。
从技术上讲,您可以通过将所有参数包装到 SetRequest
或其他内容来合并它们。
界面会有点
type Cache interface {
Set(request SetRequest) bool
}
关于go - Go 中的抽象模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49111863/