所以,我必须并行类结构,Books
和Makers
。制作者根据某个文件或其他内容创建一本书。我们可以将基本Maker的定义简化为:
class Maker {
type PF = (String, Book) => Book
def apply(in: Source): Book = {
mkMap(in, parseTop)
}
def mkMap(in: Source, top: PF) {
var res = new Book
in.getLines.foreach { ln => res = top(ln, res)
}
def parseTop(line: String, book: Book): Book = {
// really makes a new Book object with changes based on the content of `line` and returns it
book
}
}
和Book看起来像这样(不是case class
,因为我们希望能够继承它)
class Book(val title: String = "Untitled", val author: String = "No Author", val language: String = "English")
def copy(title: String = this.title, author: String = this.author, language: String = this.language) = new Book(title, author, language)
现在,我想将其扩展为制作SpecialMaker
SpecialBooks
。特别书可以这样定义:
class SpecialBook(title: String = "Untitled", author: String = "No Author", language: String = "English", val specialness: Int = 9000) extends Book(title, author, language)
def copy(title: String = this.title, author: String = this.author, language: String = this.language, specialness: Int = this.specialness) = new SpecialBook(title, author, language, specialness)
从SpecialBook
制作Book
时唯一的变化是parseTop
函数会做一些额外的计算来制作特殊因素,让我们这样说:
class SpecialMaker {
override def parseTop(line: String, book: SpecialBook): SpecialBook = {
book.copy(specialness = book.specialness + 9000)
}
}
显然,该代码不起作用,因为parseTop最终将BookBook分配给Book,以及其他问题。什么是在Scala中处理问题的最佳方法?隐含的转换? (可以与类型参数有关吗?)
如果有设计模式处理此问题,请告诉我它的名称。
答案 0 :(得分:0)