仿佛把自己坑到了不得了的地步。关于 interface

11 天前
 dzdh

做多渠道适配。其他语言的时候,基本上都是起个 interface ,实现个抽象然后改抽象。

go 也按这么来了

// 定义个接口
type I interface {
   Retrieve(s string) error
}
// 有个抽象实现
type Abstract struct {
}
func (self *Abstract) Retrieve(s string) error {
    这里有坑
}

因为是多渠道。但是各个渠道只是 api 地址不一样接口大差不差。但是多多少少有差别,但是行业标准参数名起码都一样。 然后就

type Channel1 struct { *Abstract }
type Channel2 struct { *Abstract }
type Channel3 struct { *Abstract }

func GetChan(s string) {
    switch s {
       case "1":
       	return &Channel1{&Abstract{url, apikey, mode:ws, ....}
    }
}

今天接了个需求。有 3 个渠道变了,人家比较牛逼,人家自己魔改了协议,需要重新适配。

但是,也只是修改了 2 个参数名和 URL 或者是编码。但是其他都一样。

所以。问题来了。我怎么在 Abstract.Retrieve 获取当前的实例名知道是谁被调用了(获取 str=Channel1) 😂

还是,干脆就重新写,相同的逻辑,尽管 c+v 吧。

2595 次点击
所在节点    Go 编程语言
9 条回复
zeromake
11 天前
Abstract 上挂个 Channel1 的字符串字段不行?
RayR
11 天前
接口的实现还要考虑调用者的信息。那是不是设计需要改了?
fgwmlhdkkkw
11 天前
反射或者 ctx value
pkoukk
11 天前
改架构,因为不同渠道的协议已经不一样了,Abstract 已经不 Abstract 了
wangym20804
11 天前
Channel 里面 override 啊
zacard
11 天前
在 Abstract.Retrieve 中耦合具体渠道的逻辑,明显违反了抽象原则了。直接在 channel1 ,2 ,3 覆盖 Retrieve 方法更合理,或者再抽象出个 XxxProtoAbstract ,统一处理 channel1 ,2 ,3 中相似的逻辑
zizon
10 天前
go 的抽象/interface 是面向过程/行为的.不是面向类别的.

你想复用要考虑的是一个业务逻辑里的共同行为模式.
比如
···
func Retrieve(r Retrievable) error{ .
...
}
···
linhaijian
10 天前
// 定义个接口
type I interface {
Retrieve(s string) error
Name() string
}
// 有个抽象实现
type Abstract struct {
name string
}

func (self *Abstract) Retrieve(s string) error {
这里有坑
}
func (self *Abstract) Name(s string) string {
return self.name
}

在 Retrieve 里获取 self.Name?
NessajCN
10 天前
go interface 不这么用的

type I interface {
Retrieve(s string) error
}

type Channel1 struct {...}
func (c Channel1) Retrieve(s string) error {
return nil
}

type Channel2struct {...}
func (c Channel2) Retrieve(s string) error {
return nil
}

type Channel3 struct {...}
func (c Channel3) Retrieve(s string) error {
return nil
}

func GetChan(s string, c I) {
c.Retrieve(s)
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://tanronggui.xyz/t/1107231

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX