2011-07-27 28 views
3

假设我有以下如何在Scala中建立以下关系?

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

双方战略和TestingLibrary是抽象的,因为它们需要getClosingTime通过

trait Market { 
    def getClosingTime: String 
} 

提供具体的实现可能是

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

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

val lseStrategy = new Strategy with LSE 

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

  • 战略,一个TestingLibrary
  • 战略和TestingLibrary都依赖于抽象方法getClosingTime
  • getClosingTime应该有相同的具体实施无论是在运行时
  • 战略应在构造函数中没有参数(由于进一步扩展它可能 需要被转换为特征)战略
  • 用户不应该知道什么TestingL文库

此刻,我发现在不知所措的不同选项的数量。在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();} 
} 

,但我觉得“如果”丑陋的方式做事情,因为增加了新的市场将涉及不必要的重新编译战略

回答

4

你要找的是所谓的Cake Pattern 。我仅仅链接了许多问题中的一个,并且您可以轻松地在Google上搜索许多关于此问题的博客。