go - 理解 golang 中的继承与组合
问题描述
来自Java背景,我无法理解如何使用组合来实现继承或组合如何解决继承实现的一些常见解决方案?
interface ICommand {
void Save(Records data)
Records LoadRecords()
Info GetInfo()
}
abstract class BaseCommand : ICommand {
Records LoadRecords() {
var info = GetInfo()
//implement common method.
}
}
class CommandABC : BaseCommand {
Info GetInfo(){
return info;
}
void Save(Records data){
// implement
}
}
c = new CommandABC();
c.LoadRecords(); // BaseCommand.LoadRecords -> CommandABC.Info -> Return records
c.Save(); //Command ABC.Save
我想使用组合在 Go 中实现相同的功能。毕竟这是公平的设计,应该可以很好地在 Go 中实现。
type ICommand interface {
void Save(data Records)
LoadRecords() Records
GetInfo() Info
}
type BaseCommand struct {
ICommand //no explicit inheritance. Using composition
}
func(c BaseCommand) LoadRecords() {
info := c.GetInfo()
//implement common method
}
type CommandABC struct {
BaseCommand //Composition is bad choice here?
}
func(c CommandABC) Save(data Records) {
//implement
}
func(c CommandABC) GetInfo() Info {
//implement
}
func main(){
c := CommandABC{}
c.LoadRecords(); // BaseCommand.LoadRecords -> fails to call GetInfo since ICommand is nil
c.Save(); //Command ABC.Save
}
可以这样解决
func main(){
c := CommandABC{}
c.ICommand = c //so akward. don't even understand why I am doing this
c.LoadRecords(); // BaseCommand.LoadRecords -> fails to call GetInfo since ICommand is nil
c.Save(); //Command ABC.Save
}
任何人都可以从 Go 设计的角度启发我实现这样的功能。
我的担忧/疑问更多地围绕着理解,如何使用组合来解决此类问题/代码可重用性以及更好的设计模式。
解决方案
你可以用几种不同的方式来做,但最惯用的可能是这些方面的东西。很难根据一个没有细节的人为示例给出详细的答案,并且大多数代码都被省略了,但我认为这就是你想要去的地方。
type Infoer interface {
Info GetInfo()
}
func LoadRecords(i Infoer) Records {
var info = i.GetInfo()
//implement common method.
}
type CommandABC struct {
info Info
}
func (c CommandABC) GetInfo() Info {
return c.info;
}
func (CommandABC) Save(data Records){
// implement
}
c := CommandABC{};
records := LoadRecords(c);
c.Save(records);
推荐阅读
- javascript - 当字符串在双引号内有单引号时,如何在Javascript中将此字符串转换为JSON对象
- excel - Workbook.close 导致 sub 退出
- c++ - 如何运行 Wave 快速入门示例?
- vba - PowerPoint 加载项 将文本框添加到所选幻灯片
- c# - 在实现具有默认方法实现的接口的类上使用`GetMethod`返回null
- c# - LINQ 在更大的集合中找到一组值的 MAX 值
- mysql - 执行灵活搜索查询时无法评估表达式方法引发“java.lang.illegalargumentexception”异常
- android - 无法使用 FileProvider 与其他应用共享图像文件
- javascript - 网页上的 Javascript 空白页
- node.js - 查询 MongoDB 问题