Idiomatic Go相当于子类

时间:2016-01-06 15:13:05

标签: c++ design-patterns go

我在C ++方面比Go有更多的经验。我试图了解如何在Go中以惯用方式表达Composite design pattern,特别是参考属性。在C ++中,我使用父类来保存一组子类共有的属性和方法。我没有看到这在Go中如何运作。接口允许我定义要实现的方法,但它不允许我提供默认实现。我必须在实现接口的每个结构中重新实现该方法,并复制每个结构中的所有属性。我不能在接口中保留公共属性,因为接口没有数据元素。你如何在Go中进行这种重构?

以下是我希望在Go中能够做到的一个例子(在C ++中):

#include <string>

/*
 * Parent class for edible things. Holds the "name" attribute.
 */

class Edible {
public:
        Edible(const std::string &aName):
                ed_Name(aName) { }
        const std::string &name() const { return ed_Name; }

protected:
        void setName(const std::string &aName) { ed_Name = aName; }

private:
        std::string ed_Name;
};

/*
 * Subclass of Edible for fruits. Depends on Edible to store the name.
 */

class Fruit: public Edible {
public:
        Fruit(const std::string &aName,
              const std::string &aPlant):
                Edible(aName),
                fr_Plant(aPlant) { }
        const std::string &plant() const { return fr_Plant; }

protected:
        void setPlant(const std::string &aPlant) { fr_Plant = aPlant; }

private:
        std::string fr_Plant;
};

/*
 * Subclass of Edible for meats. Depends on Edible to store the name.
 * Has attributes for the animal and the cut of meat.
 */

class Meat: public Edible {
public:
        Meat(const std::string &aName,
             const std::string &aAnimal,
             const std::string &aCut):
                Edible(aName),
                me_Animal(aAnimal),
                me_Cut(aCut) { }
        const std::string &animal() const { return me_Animal; }
        const std::string &cut() const { return me_Cut; }
protected:
        void setAnimal(const std::string &aAnimal) { me_Animal = aAnimal; }
        void setCut(const std::string &aCut) { me_Cut = aCut; }
private:
        std::string me_Animal;
        std::string me_Cut;
};

1 个答案:

答案 0 :(得分:1)

在这种情况下,您可以拥有一个Edible界面,以及type Fruit structtype Meat struct各自实施的界面。其中每个也可以组成,它包含一个EdibleName,它将提供设置/获取名称的方法和存储空间。

e.g。

type Edible interface {
    eat() int // common method
}

type EdibleName struct {
    name string
}

// NB getters and setters may not be idiomatic
func (n *EdibleName) getName() string {
    return n.name
}

func (n *EdibleName) setName(name string) {
    n.name = name
}

type Fruit struct {
    pips int
    EdibleName
}

func (f *Fruit) eat() int {
    // ...
    return 0
}

type Meat struct {
    animal int
    EdibleName
}

func (m *Meat) eat() int {
    animal int
    return 0
}