Suppose I have the following
abstract class Strategy {
val lib: TestingLibrary = ...
}
Both Strategy and TestingLibrary are abstract because they require getClosingTime provided by
trait Market {
def getClosingTime: String
}
A specific implementation might be
trait LSE extends Market {
def getClosingTime = "16:35:00"
}
At runtime, I want to be able to specify that a particular Strategy and TestingLibrary are both using LSE. This means that when getClosingTime is called on either, they should both have a concrete implementation returning "16:35:00". I was thinking of something like
val lseStrategy = new Strategy with LSE
I would like to stick to traits if possible but don't know how to mixin LSE with TestingLibrary. Perhaps my entire approach needs to be modified but the main business rules are:
- Strategy has-a TestingLibrary
- Strategy and TestingLibrary both rely on the abstract method getClosingTime
- getClosingTime should have the same concrete implementation for both at runtime
- Strategy should take no parameters in the constructor (due to further extensions it may need to be converted to a trait)
- Users of Strategy should not know anything about TestingLibrary
At the moment I'm finding the number of different options in bewildering. In Java I did something like the following
class LSETestingLibrary extends TestingLibrary {
String getClosingTime {return "16:35:00"}
}
class Strategy {
TestingLibrary lib;
Strategy(Market market) {
if (market == LSE) lib = new LSETestingLibrary();
}
String getClosingTime { return lib.getClosingTme();}
}
but I find the "if" an ugly way to do things since adding new markets would involve unnecessarily recompiling Strategy