我在 C++ 方面的經驗比 Go 多得多。我試圖了解復合設計模式如何在 Go 中以慣用方式表達,特別是在參考屬性方面。在 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 回答

瀟瀟雨雨
TA貢獻1833條經驗 獲得超4個贊
在這種情況下,你可以有一個Edible接口,并且type Fruit struct和type 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
}
- 1 回答
- 0 關注
- 240 瀏覽
添加回答
舉報
0/150
提交
取消