首页 > 解决方案 > 理解 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 设计的角度启发我实现这样的功能。

我的担忧/疑问更多地围绕着理解,如何使用组合来解决此类问题/代码可重用性以及更好的设计模式。

标签: goinheritancecomposition

解决方案


你可以用几种不同的方式来做,但最惯用的可能是这些方面的东西。很难根据一个没有细节的人为示例给出详细的答案,并且大多数代码都被省略了,但我认为这就是你想要去的地方。

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);

推荐阅读