2017-12-05 4 views
0

나는이 있습니다 프로젝트) :스칼라 케이크 패턴과 멀티 프로젝트

object MyOtherApp { 
    trait MyOtherTableName extends DBTableNamesProvider 
    val MyCustomService = MyService() with MyOtherTableName // will not compile how to reuse the module's MyService() with another implementation of one of the traits? 
} 

가 위의 난 그냥이면 MyService() 건설을 호출하고 의존성의 일부를 재정의 할 수 없습니다 컴파일되지 않습니다.

위의 내용은 MyProjectATableNames의 자체 구현과 함께 적용되는 MyService()의 공장 구성이 다른 프로젝트에서 재정의하려는 경우 스칼라에서 가능합니까? 코드 반복없이 권장되는 방법은 무엇입니까?

답변

1
val MyCustomService = new MyService() with MyOtherTableName 

당신은 또한 DefaultDBProviderDefaultTableNames에서 상속 할 경우

작동합니다, 당신은해야 할 것 명시 적으로뿐만 아니라 그들을 목록 :

val MyCustomService = new MyService() with MyOtherTableName with DefaultDBProvider with DefaultTableNames 

을하거나의 중간 특성을 만들 공통 라이브러리 :

trait DefaultService extends MyService with DefaultDBProvider with DefaultTableNames 
0

MyService()이 더 이상 유형이 아닌 개체이므로 더 이상 생성 된 유형을 재정의 할 수 없습니다. 그래서 코드를 재사용하는 당신은 당신이

object MyService { 
    def apply() = new ConfiguredMyService 
} 

를 선언 할 수있는 최초의 응용 프로그램에

class ConfiguredMyService extends DefaultDBProvider with DefaultTableNames 

같은 클래스를 만들 수 있습니다 및 제

val MyCustomService = new ConfiguredMyService with MyOtherTableName 

참고 : 요즘, 케이크 패턴입니다 안티 패턴으로 간주되므로, Checkout Dependency Injection을 추천합니다.

+0

'MyService'는 특성이며, 그것을 익명으로 좋아하는 경향이 있습니다. 또한, Play를 좋아하는 두 블로거의 의견을 제외하고는 케이크 패턴에 아무런 문제가 없습니다. – Dima