go - Go 中的抽象模式

标签 go interface abstraction

我有两个接口(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/

相关文章:

正则表达式将字符串golang中的子字符串更改为大写

google-app-engine - 我的数据存储 PropertyLoadSaver 在 golang 中不起作用

java - 枚举默认方法

Python错误 "<method> missing 1 required positional argument: ' self '“

go - Atom Editor 1.15.0 with Go-Plus 在函数源代码中有红色背景

oracle - 如何在 Go 语言中从 Oracle(长原始格式)读取图像

c# - 隐式与显式接口(interface)实现

java - 缩进接口(interface)的多个实现的公认做法是什么

c++ - 操作系统提供的抽象

c++ - 如何使 C++ 类以 const 方式访问所有另一个类的私有(private)成员(只读不写)