Better alternative to Strategy pattern in Scala? -
when i'm programming in java (or similar language), employ simple version of strategy pattern, using interfaces , implementation classes, provide runtime-selectable implementations of particular concept in code.
as contrived example, might want have general concept of animal can make noise in java code, , want able select type of animal @ runtime. write code along these lines:
interface animal { void makenoise(); } class cat extends animal { void makenoise() { system.out.println("meow"); } } class dog extends animal { void makenoise() { system.out.println("woof"); } } class animalcontainer { animal myanimal; animalcontainer(string whichone) { if (whichone.equals("cat")) myanimal = new cat(); else myanimal = new dog(); } void doanimalstuff() { ... // time animal make noise myanimal.makenoise(); ... }
simple enough. recently, though, i've been working on project in scala , want same thing. seems easy enough using traits, this:
trait animal { def makenoise:unit } class cat extends animal { override def makenoise:unit = println("meow") } class animalcontainer { val myanimal:animal = new cat ... }
however, seems java-like , not functional--not mention traits , interfaces aren't really same thing. i'm wondering if there's more idiomatic way implement strategy pattern--or it--in scala code can select concrete implementation of abstract concept @ runtime. or using traits best way achieve this?
you can variation on cake pattern.
trait animal { def makenoise: unit } trait cat extends animal { override def makenoise { println("meow") } } trait dog extends animal { override def makenoise { println("woof") } } class animalcontaineer { self: animal => def doanimalstuff { // ... makenoise // ... } } object strategyexample extends application { val ex1 = new animalcontainer dog val ex2 = new animalcontainer cat ex1.doanimalstuff ex2.doanimalstuff }
in terms of strategy pattern, self type on strategy indicates must mixed specific implementation of sort of algorithm.
Comments
Post a Comment