如何在Scala中建模以下关系?

时间:2011-07-27 22:00:29

标签: scala

假设我有以下

abstract class Strategy {
    val lib: TestingLibrary = ...
}

策略和TestingLibrary都是抽象的,因为它们需要

提供的getClosingTime
trait Market {
    def getClosingTime: String
}

具体实施可能是

trait LSE extends Market {
    def getClosingTime = "16:35:00"
}

在运行时,我希望能够指定特定的策略和TestingLibrary都使用LSE。这意味着当调用getClosingTime时,它们都应该具有返回“16:35:00”的具体实现。我在考虑像

这样的东西
val lseStrategy = new Strategy with LSE

如果可能,我想坚持特性,但不知道如何将LSE与TestingLibrary混合。也许我的整个方法需要修改,但主要的业务规则是:

  • 策略有一个TestingLibrary
  • 策略和TestingLibrary都依赖于抽象方法getClosingTime
  • getClosingTime应该在运行时具有相同的具体实现
  • 策略应该不在构造函数中使用任何参数(由于它可能会进一步扩展) 需要转换为特质)
  • 策略用户不应该对TestingLibrary了解任何信息

目前我发现令人眼花缭乱的不同选择的数量。在Java中,我做了类似下面的内容

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();}
}

但是我发现“if”是一种丑陋的做事方式,因为增加新市场将涉及不必要地重新编译策略

2 个答案:

答案 0 :(得分:4)

您正在寻找的是Cake Pattern。我只链接了很多问题中的一个,你可以轻松地谷歌搜索很多博客。

答案 1 :(得分:2)

Scala允许您使用OOP样式和FP样式。使用OO风格,你会使用Cake Pttern,如Daniel建议的那样。这是一个很好的概述 - OO / FP(包括示例代码)之间的比较:http://debasishg.blogspot.com/2011/03/pushing-envelope-on-oo-and-functional.html