Created
August 2, 2015 04:20
-
-
Save sohlich/7aec3fef036b71c8e80e to your computer and use it in GitHub Desktop.
Example of decorator pattern in GO
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" | |
"log" | |
) | |
//Basic interface to be enriched | |
type GreetingsBot interface { | |
DoHail(name string) (string, error) | |
} | |
//Nested functions not allowed so the function must be as type | |
type Hail func(name string) (string, error) | |
func (hail Hail) DoHail(name string) (string, error) { | |
return hail(name) | |
} | |
//Enrich the interface without interference to original code | |
type Decorator func(bot GreetingsBot) GreetingsBot | |
// | |
func LogDecorator(component string) Decorator { | |
return func(bot GreetingsBot) GreetingsBot { | |
return Hail(func(name string) (string, error) { | |
log.Printf("[%s] :Call logging", component) | |
return bot.DoHail(name) | |
}) | |
} | |
} | |
type EnglishBot struct{} | |
func (bot *EnglishBot) DoHail(name string) (string, error) { | |
fmt.Printf("Hello %s \n", name) | |
return "Hello", nil | |
} | |
func main() { | |
helloBot := LogDecorator("Hailer")(&EnglishBot{}) | |
//helloBot is enriched client with Logging function | |
helloBot.DoHail("Radek") | |
helloBot.DoHail("Tereza") | |
helloBot.DoHail("Tobias") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment