去的抽象模式

问题描述 投票:-4回答:2

我有两个接口。它们几乎相同,唯一的区别是Set方法:

type Cache1 interface {
    Set(key, value interface{}, ttl time.Duration) bool
}

type Cache2 interface {
    Set(key, value interface{}) bool
}

知道如何将它们统一到一个抽象中吗?当然我可以将ttl time.Duration添加到第二个界面,但它将无用,并会恶化代码可读性。如果存在复杂的模式,请你建议吗?

go interface abstraction
2个回答
2
投票

我猜,在合并这些方法时你应该关注接口隔离原理。

从技术上讲,您可以通过将所有参数包装到SetRequest或其他东西来合并它们。接口将是一种

type Cache interface {
    Set(request SetRequest) bool
}

0
投票

刚想到的另一个机会是联合接口到一个:

type Cache interface {
    Set(key, value interface{}, ttl time.Duration) bool
}

如有必要,请忽略方法签名中的冗余参数:

func (c *cache) Set(key, value interface{}, _ time.Duration) bool {
© www.soinside.com 2019 - 2024. All rights reserved.