Created
June 21, 2019 10:01
-
-
Save jonleopard/a1e87b5157262fe3c7ea89b91b9082ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Cat struct{} | |
func (c Cat) Speak() { | |
fmt.Println("meow") | |
} | |
type Dog struct{} | |
func (d Dog) Speak() { | |
fmt.Println("woof") | |
} | |
type Husky struct { | |
Speaker | |
} | |
type SpeakerPrefixer struct { | |
Speaker | |
} | |
func (sp SpeakerPrefixer) Speak() { | |
fmt.Print("Prefix: ") | |
sp.Speaker.Speak() | |
} | |
type Speaker interface { | |
Speak() | |
} | |
// 'Husky' type doesn't what Speaker type it gets | |
// as long as it gets some sort of Speaker type | |
// E.g. You can swap out Dog{} with Cat{}. | |
func main() { | |
h := Husky{SpeakerPrefixer{Dog{}}} | |
// Whenever you call h.Speak() it calls | |
// the SpeakerPrefixer Speak method, and then | |
// that eventually calls sp.Speaker.Speak method. | |
// Husky doesn't know or care about it since it just | |
// needs some sort of Speak method to call. | |
h.Speak() | |
} | |
// This is not inheritance, this is 'embedding' | |
// https://www.youtube.com/watch?v=F4wUrj6pmSI&feature=youtu.be&t=1337 | |
// Call Dispatch | |
// | |
// Concrete Types: static Abstract types: dynamic | |
// - known at compilcation - unknown at compilcation | |
// - very efficient - less efficient | |
// - can't intercept - easy to intercept |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment