Created
February 21, 2012 05:08
-
-
Save kencoba/1873880 to your computer and use it in GitHub Desktop.
AbstractFactory pattern with Scala
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
/** | |
* 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