Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created February 21, 2012 05:08
Show Gist options
  • Save kencoba/1873880 to your computer and use it in GitHub Desktop.
Save kencoba/1873880 to your computer and use it in GitHub Desktop.
AbstractFactory pattern with Scala
/**
* Example of AbstractFactory pattern
*
* create OS Specific GUIWidget with same operation.
*
*/
trait Button {
def paint: String
}
class WinButton extends Button {
def paint: String = "I'm a WinButton"
}
class OSXButton extends Button {
def paint: String = "I'm a OSXButton"
}
trait GUIFactory {
def createButton: Button
}
class WinFactory extends GUIFactory {
def createButton: Button = new WinButton
}
class OSXFactory extends GUIFactory {
def createButton: Button = new OSXButton
}
class Application(factory: GUIFactory) {
val button = factory.createButton
println(button.paint)
}
object ApplicationRunner {
def main(argv: Array[String]) {
new Application(createOsSpecificFactory(argv(0)))
}
def createOsSpecificFactory(os_type: String): GUIFactory = {
os_type match {
case "Win" => new WinFactory
case "OSX" => new OSXFactory
}
}
}
ApplicationRunner.main(Array("Win"))
ApplicationRunner.main(Array("OSX"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment