成语Go等同于子类

斯科特·迪尔韦斯特(Scott Deerwester):

与Go相比,我在C ++方面拥有更多的经验。我试图了解如何在Go中惯用地表达Composite设计模式,尤其是参考属性。在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;
};
正确的:

在这种情况下,你可以有一个Edible接口,并且type Fruit structtype Meat struct每个执行它们。每一个都可以组成一个包含一个的EdibleName,后者将提供设置和获取名称的方法和存储空间。

例如

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
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章