Interfaces, Class Composition, Diamond Problem
Posted on February 2, 2022
Tags: softdev
- Composition can be visualized as a tree
- Composing classes can be thought of as embedding or inserting a class into another class
- “Embed a Engine class inside a Car class” == “Insert a Engine class inside a Car class”
- Golang calls this struct embedding
1 AbstractClass/Interface vs Composition
- Inheritance: AbstractClass/Interface are the subset of the group intersection of multiple classes
- Composition: Classes may be composed of the same component which is the group intersection of multiple classes
- Notice how Composition and Inheritance are basically the same in functionality.
2 Interface Composition
- \(f(g(),h(i(),j()))\) \(f\) is ReadAll and it has it’s own type called ReadAll_attr along with composing \(g\) and \(h(i(),j())\) which are ReadRPC and ReadREST respectively.
type ReadJSON interface {
...
}
type ReadXML interface {
...
}
type ReadREST interface {
string
ReadREST_attr
ReadJSON
ReadXML}
type ReadRPC interface {
...
}
type ReadAll interface{
string
ReadAll_attr
ReadRPC
ReadREST}
3 Class composition
type Wheel struct {
...
}
type Engine struct {
}
type Car struct {
string
name
Engine
Wheel}