Last active
December 24, 2015 10:09
-
-
Save dfox/6781668 to your computer and use it in GitHub Desktop.
Externalizing configuration values using the Cake Pattern
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
/* Standard component trait a-la cake */ | |
trait MessagePrinterComponent { | |
def printer: MessagePrinter | |
trait MessagePrinter{ | |
def printMessage(message: String) | |
} | |
} | |
/* A trait to encapsulate implementation-specific configuration */ | |
trait MessagePrinterConfig { | |
val borderChar: String | |
} | |
/* The component implementation and trait wrapper a-la cake */ | |
trait MyMessagePrinterComponent extends MessagePrinterComponent { | |
this: MessagePrinterConfig => | |
def printer = new MyMessagePrinter | |
class MyMessagePrinter extends MessagePrinter { | |
def printMessage(message: String) = { | |
val border = borderChar * (message.length + 4) | |
println(border) | |
println(borderChar + " " + message + " " + borderChar) | |
println(border) | |
} | |
} | |
} | |
/* The actual configuration we'll use which could be put perhaps in a "config" package */ | |
trait MyMessagePrinterConfig extends MessagePrinterConfig{ | |
val borderChar = "*" | |
} | |
/* The app which demonstrates using the component with its configuration */ | |
object Cli extends App { | |
val printerComponent = new MyMessagePrinterComponent with MyMessagePrinterConfig | |
printerComponent.printer.printMessage("foobar") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment