理解 golang 中的继承与组合

问题描述 投票:0回答:1

来自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 设计的角度实现这样的功能吗?

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

go inheritance composition
1个回答
2
投票

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

type Infoer interface {
   GetInfo() Info
}

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);
© www.soinside.com 2019 - 2024. All rights reserved.