Skip to content

Instantly share code, notes, and snippets.

@Mortimerp9
Created October 12, 2013 16:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mortimerp9/6952000 to your computer and use it in GitHub Desktop.
Save Mortimerp9/6952000 to your computer and use it in GitHub Desktop.
An alternative Factory pattern in Scala to compare with the one presented in [Design Patterns in Scala](http://pavelfatin.com/design-patterns-in-scala/). This one involves a bit more boilerplate, but will not compile if you ask for an unknown type and is easier to extend.
trait Animal
private class Dog extends Animal
private class Cat extends Animal
trait Wanna
case object WannaCat extends Wanna
case object WannaDog extends Wanna
trait AnimalFactory[Wanna] {
def create(): Animal
}
object Animal {
def apply[T <: Wanna](kind: T)(implicit factory: AnimalFactory[T]) =
factory.create()
}
implicit val canMakeCat = new AnimalFactory[WannaCat.type] {
def create(): Animal = new Cat()
}
implicit val canMakeDog = new AnimalFactory[WannaDog.type] {
def create(): Animal = new Dog()
}
@Mortimerp9
Copy link
Author

You can then create animals with:

scala> val cat = Animal(WannaCat)
cat: Animal = Cat@46a1d830

scala> val dog = Animal(WannaDog)
dog: Animal = Dog@1afa463f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment