Skip to content

Instantly share code, notes, and snippets.

@AlexRogalskiy
Last active December 19, 2020 19:56
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 AlexRogalskiy/f325b1777e6af4381a10776ff7f53420 to your computer and use it in GitHub Desktop.
Save AlexRogalskiy/f325b1777e6af4381a10776ff7f53420 to your computer and use it in GitHub Desktop.
Scala Pattern: factory method
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()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment