deltanovember
deltanovember

Reputation: 44051

How do I model the following relationship in Scala?

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:

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

Upvotes: 3

Views: 178

Answers (2)

AndreasScheinert
AndreasScheinert

Reputation: 1918

Scala allows you to use OOP style and FP Style. With OO style you would use the Cake Pttern as Daniel suggested. Here is a nice overview- comparison between OO/FP (including example code): http://debasishg.blogspot.com/2011/03/pushing-envelope-on-oo-and-functional.html

Upvotes: 2

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297205

What you are looking for is called the Cake Pattern. I'm linking just one of many questions, and you can easily google many blogs about it.

Upvotes: 4

Related Questions