Skip to content

Instantly share code, notes, and snippets.

@lukebayes
Created May 7, 2018 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukebayes/ae7eb488a30130cb84cc6f43b4c29629 to your computer and use it in GitHub Desktop.
Save lukebayes/ae7eb488a30130cb84cc6f43b4c29629 to your computer and use it in GitHub Desktop.
Embed != Inherit
package main
import (
"fmt"
)
type Displayable interface {
AddChild(c Displayable)
ChildAt(index int) Displayable
SetParent(p Displayable)
Parent() Displayable
Render()
Draw()
}
// DisplayObject implements the Displayable interface
type DisplayObject struct {
children []Displayable
parent Displayable
}
func (b *DisplayObject) AddChild(child Displayable) {
b.children = append(b.children, child)
// This is the call that stores *DisplayObject, not *Rectangle.
child.SetParent(b)
}
func (b *DisplayObject) SetParent(p Displayable) {
b.parent = p
}
func (b *DisplayObject) Parent() Displayable {
return b.parent
}
func (b *DisplayObject) ChildAt(index int) Displayable {
return b.children[index]
}
func (b *DisplayObject) Render() {
fmt.Println("DisplayObject.Render")
}
func (b *DisplayObject) Draw() {
fmt.Println("DisplayObject.Draw")
}
// Sub is a child struct of the Base an overridden concrete
// implementation.
type Rectangle struct {
DisplayObject
}
func (s *Rectangle) Draw() {
fmt.Println("Rectangle.Draw")
}
func NewRectangle() Displayable {
return &Rectangle{}
}
func main() {
fmt.Println("-----------------")
fmt.Println("Before Children:")
r := NewRectangle()
r.Render() // DisplayObject.Render
r.Draw() // Rectangle.Draw
fmt.Println("-----------------")
fmt.Println("Create Children")
root := NewRectangle()
one := NewRectangle()
two := NewRectangle()
root.AddChild(one)
root.AddChild(two)
fmt.Println("-----------------")
fmt.Println("From Children:")
child2 := root.ChildAt(1)
child2.Render() // DisplayObject.Render
child2.Draw() // Rectangle.Draw
fmt.Println("-----------------")
fmt.Println("From Parent:")
fromParent := child2.Parent()
fromParent.Render() // DisplayObject.Render
fromParent.Draw() // DisplayObject.Draw (SURPRISE! Expected Rectangle.Draw!)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment