0
일부 요소의 인스턴스 (내부 형식)를 만드는 팩토리 개체가 있습니다. 또한 공장에서 만든 요소에서 작동하는 작업이 있습니다.추상 클래스를 사용하지 않고 형식 유추를 수행하는 방법
class Factory {
class Element private [Factory] (val int:Int)
def create(from:Int) = new Element(from)
}
class OperationOnFactoryElement(val factory:Factory) {
def apply(element:factory.Element) = factory.create(element.int + 1)
}
val factory = new Factory
val op = new OperationOnFactoryElement(factory)
val someElement = factory.create(1)
op(someElement) // this causes an error!!
//<console>:13: error: type mismatch;
// found : factory.Element
// required: op.factory.Element
// op(someElement)
// ^
컴파일러가 작업을 허용하도록 OperationOnFactoryElement
에 포함 된 공장을 사용하는 날을 기대하고 분명하다 : 여기에 코드입니다. 그러나 그 요소에 대해 더 많은 연산을 정의해야한다면, 예를 들어 두 연산을 결합 할 수 없기 때문에 문제가됩니다. 이 솔루션을 생각해 냈습니다 :
class Factory {
class Element private [Factory] (val int:Int)
def create(from:Int) = new Element(from)
}
abstract class OperationOnFactoryElement {
val factory:Factory
def apply(element:factory.Element) = factory.create(element.int + 1)
}
val myfactory = new Factory
val op = new OperationOnFactoryElement {
val factory:myfactory.type = myfactory
}
val someElement = myfactory.create(1)
op(someElement) // this works
그러나 저는 작업을 추상 클래스로 변경해야합니다. 내 질문 :
클래스를 만들지 않고 같은 결과를 얻을 수있는 방법이 있나요 OperationOnFactoryElement
추상?