Skip to content

Instantly share code, notes, and snippets.

@dfox
Last active December 24, 2015 10:09
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 dfox/6781668 to your computer and use it in GitHub Desktop.
Save dfox/6781668 to your computer and use it in GitHub Desktop.
Externalizing configuration values using the Cake Pattern
/* 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