我正在研究Scala中的工厂设计模式。这种方法的好处之一是对象创建逻辑和客户端之间的松散耦合(来自http://www.journaldev.com/10350/factory-design-pattern-in-scala)。我们怎样才能实现这一目标以及为什么我们需要松耦合呢?有人可以提供一些例子并解释一下吗?
答案 0 :(得分:0)
据我了解,您正在Scala中寻找有关Factory Pattern的示例,您可以找到带有一些简单示例here
的用例。在创建API库类(其他类可以使用的类)时,工厂模式更有用。希望下面的例子能清楚地解释它,
trait ContentAPI {
def getContentById(id : Int) : String
def getContentByTitle(title: String) : String
def getAllContent(title: String) : String }
object ContentAPI {
protected class ContentAPI(config: APIConfig) extends PageContentAPI {
/**
* get all content of a page parsing the page title
*
* @param query title parsed
* @return all content as a String
*/
override def getAllContent(query: String) : String = {
var pageContent: String = " Some text"
pageContent
}
/**
* get only the content body text parsing the page title
*
* @param query title parsed
* @return content as a String
*/
override def getContentByTitle(query: String) : String = {
var pageContent: String = " Some String "
pageContent
}
/**
* get only the content body text parsing the page id
*
* @param query id parsed
* @return content as a string
*/
override def getContentById(query: Int) : String
var pageContent: String = "some string"
pageContent
}
}
class APIConfig(path: String) {
val inputPath = path
}
/** Configuration object for the Content API */
object APIConfig {
protected class APIConfigBuilder(dataPath: String) {
def setDataPath(path: String): APIConfigBuilder = {
new APIConfigBuilder(path)
}
def getOrCreate(): APIConfig = {
new APIConfig(dataPath)
}
}
def withBuilder(): APIConfigBuilder = {
new APIConfigBuilder("")
}
}
def apply(config: APIConfig): ContentAPI = {
new ContentAPI(config)
}
}
/** Client Object */
object APIClient{
def main(args: Array[String]): Unit = {
import Arguments.WIKI_DUMP_BASE
val dataPath = "path"
val contentAPI = ContentAPI(APIConfig.withBuilder().setDataPath(dataPath).getOrCreate())
contentAPI.getAllContent("Anarchism").show()
contentAPI.getContentByTitle("Anarchism").show()
contentAPI.getContentById(12).show()
}
}