Created
April 7, 2016 11:27
-
-
Save AlexanderChen1989/2e9b7cae191fb3b2612b1d87e03f5246 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 "log" | |
type AB interface { | |
Append(AB) AB | |
DoA() | |
DoB() | |
} | |
// empty | |
type empty struct{} | |
func (ab empty) Append(AB) AB { | |
return empty{} | |
} | |
func (ab empty) DoA() {} | |
func (ab empty) DoB() {} | |
// log | |
type logAB struct { | |
AB | |
} | |
func (l logAB) Append(ab AB) AB { | |
l.AB = ab | |
return l | |
} | |
func (l logAB) DoA() { | |
log.Println("DoA") | |
l.AB.DoA() | |
} | |
func (l logAB) DoB() { | |
log.Println("DoB") | |
l.AB.DoB() | |
} | |
func Compose(abs ...AB) AB { | |
if len(abs) <= 0 { | |
return empty{} | |
} | |
ab := abs[len(abs)-1] | |
for i := len(abs) - 2; i >= 0; i-- { | |
ab = abs[i].Append(ab) | |
} | |
return ab | |
} | |
func main() { | |
ab := Compose(logAB{}, logAB{}, empty{}) | |
ab.DoA() | |
ab.DoB() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment