我有两个接口。它们几乎相同,唯一的区别是Set
方法:
type Cache1 interface {
Set(key, value interface{}, ttl time.Duration) bool
}
type Cache2 interface {
Set(key, value interface{}) bool
}
知道如何将它们统一到一个抽象中吗?当然我可以将ttl time.Duration
添加到第二个界面,但它将无用,并会恶化代码可读性。如果存在复杂的模式,请你建议吗?
我猜,在合并这些方法时你应该关注接口隔离原理。
从技术上讲,您可以通过将所有参数包装到SetRequest
或其他东西来合并它们。接口将是一种
type Cache interface {
Set(request SetRequest) bool
}
刚想到的另一个机会是联合接口到一个:
type Cache interface {
Set(key, value interface{}, ttl time.Duration) bool
}
如有必要,请忽略方法签名中的冗余参数:
func (c *cache) Set(key, value interface{}, _ time.Duration) bool {