Go 中的抽象模式

Abstraction patterns in go

我有两个接口。它们几乎相同,唯一的区别是 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 {