[翻譯]Effective Java in Kotlin:1. 考慮用靜態工廠方法而不是構造器

原文: Effective Java in Kotlin, item 1: Consider static factory methods instead of constructorsjava

Book reminder

Effective Java 的第一條規則:開發者應該考慮用靜態工廠方法而不是構造器。靜態工廠方法指使用靜態方法來生成類的實例。下面是Java中靜態工廠方法使用示例:數組

Boolean trueBoolean = Boolean.valueOf(true);
String number = String.valueOf(12);
List<Integer> list = Arrays.asList(1, 2, 4);
複製代碼

靜態工廠方法使用來改造構造器的有力方法,下面是一些使用靜態工廠方法的好處:緩存

  • 與構造器不一樣,靜態工廠方法是具名的。 方法名解釋了實例是如何被建立的以及參數是什麼。舉個例子new ArrayList(3)3所表明的意思就不明確,你能夠認爲它是數組的第一個元素或者是數組的大小。換作是靜態工廠方法ArrayList.withSize(3),表達的意思就很是明確。具名方法的一個好處是:它解釋了參數的含義或者在某種程度上揭示了實例被建立的機制。另外一個好處是解決了相同參數類型的構造方法之間的混淆。
  • 與構造器不一樣,靜態工廠方法並非每次被調用都會建立新的實例。當咱們使用靜態工廠方法時可使用緩存機制去優化實例的建立,從而提升實例建立的性能。一樣咱們能夠定義相似Connectrions.createOrNull()這樣的方法,使其在Connection不能創建時返回null
  • 與構造器不一樣,靜態工廠方法能夠返回任一子類型。這一特性能夠用來在不一樣狀況下提供更合適的實例,幫助咱們隱藏接口背後的真正實例。在Kotlin中全部的集合都隱藏在接口背後。好比listOf(1,2,3), 當運行在Kotlin/JVM平臺時會返回ArrayList,當運行在Kotlin/JS平臺時會返回JavaScript array (這兩種類型都實現了KotlinList接口)。一般狀況下咱們要操做的是接口,隱藏在接口下的具體實現有時並不重要。簡單地說,靜態工廠方法能夠返回超類型的任意子類型,甚至改變類型的某些實現。
  • 減小了建立參數化類型實例的冗長。Kotlin在某種程度上解決了這個問題,由於Kotlin有更好的類型推斷。

Joshua Bloch 指出了靜態工廠方法的一些缺點:app

  • 靜態工廠方法不能被用於子類的構造。在子類的構造中須要使用超類的構造器,而咱們並不能使用靜態工廠方法去替代
  • 靜態工廠方法不容易和其餘靜態方法進行區分。好比valueOf, of, getInstance, newInstance, getTypenewType, 這些都是很常見的靜態工廠方法的命名。

直觀的結論: 當構造方法和實例自己結構具備很強的關聯時應該使用構造器;反之,應該使用靜態工廠方法ide

在Kotlin當中, Kotlin改變了靜態工廠方法的實現途徑。性能

Companion factory method

Kotlin中不容許靜態方法,Java中的靜態工廠方法在Kotlin中一般被伴生工廠方法(Companion factory method)所取代。伴生工廠方法指被放入伴生對象中的工廠方法:測試

class MyList {
    //...
    companion object {
        fun of(vararg i: Int) { /*...*/ }
    }
}
複製代碼

使用方法和靜態工廠方法相同:優化

MyList.of(1,2,3,4)
複製代碼

實際上伴生對象是一個單例類,這就致使了伴生對象是能夠繼承其餘類的。這樣咱們就能夠實現多個通用的工廠方法而後給他們提供不一樣的類。Provider類是一個輕量的用於依賴注入的類:ui

abstract class Provider<T> {
    var original: T? = null
    var mocked: T? = null
    abstract fun create(): T
    fun get(): T = mocked ?: original ?: create().apply { original = this }
    fun lazyGet(): Lazy<T> = lazy { get() }
}
複製代碼

對於不一樣的類,只須要提供特定的構造方法:this

interface UserRepository {
    fun getUser(): User
    companion object: Provider<UserRepository> {
        override fun create() = UserRepositoryImpl()
    }
}
複製代碼

而後咱們就可使用UserReposiroty.get()來獲取實例,或者使用val user by UserRepository.lazyGet()進行懶加載。另外還能夠聲明特定的實現用於測試或進行Mock

UserRepository.mocked = object: UserRepository { /*...*/ }
複製代碼

相比於Java來說這是一個巨大的優點,在Java中靜態工廠方法必須在每一個類中手動實現。另一種複用工廠方法的方式是經過接口代理(interface delegation),咱們能夠以以下的方式使用上述例子:

interface Dependency<T> {
    var mocked: T?
    fun get(): T
    fun lazyGet(): Lazy<T> = lazy { get() }
}
abstract class Provider<T>(val init: ()->T): Dependency<T> {
    var original: T? = null
    override var mocked: T? = null
     
    override fun get(): T = mocked ?: original ?: init()
          .apply { original = this }
}
interface UserRepository {
    fun getUser(): User
    companion object: Dependency<UserRepository> by Provider({
        UserRepositoryImpl() 
    }) 
}
複製代碼

Extension factory methods

將工廠方法放入伴生對象中的另外一個好處是:咱們能夠定義伴生對象的擴展方法。所以咱們能夠給外部依賴來添加伴生工廠方法(前提是外部依賴定義了伴生對象):

interface Tool {
   companion object { … }
}
fun Tool.Companion.createBigTool(…) : BigTool { … }
複製代碼

或者是具名的伴生對象

interface Tool {
   companion object Factory { … }
}
fun Tool.Factory.createBigTool(…) : BigTool { … }
複製代碼

Top-level functions

在Kotlin中,使用頂層方法(Top-level functions)來取代伴生工廠方法也很常見,好比listOf,setOf,mapOf。 庫的設計者也常常提供頂層方法來建立實例。舉個例子,Android開發中,傳統的方法是使用靜態方法去建立Activity Intent:

// Java
class MainActivity extends Activity {
    static Intent getIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }
}
複製代碼

在kotlin Anko庫中,咱們使用頂層方法intentFor

intentFor<MainActivity>()
複製代碼

使用頂層方法的問題在於,公有的頂層方法是處處能夠訪問的,很容易就「污染了」IDE的智能提示。

儘管使用公有的頂層方法須要謹慎,對於一些小的常常須要建立的實例(好比List Map)使用頂層方法是一個很好的選擇,由於listOf(1,2,3)要比List.of(1,2,3)更簡單更具備可讀性。

Fake constructors

構造器在Kotlin中的使用方式和頂層方法相似(Kotlin中不須要new關鍵字):

class A()
val a = A()
複製代碼

構造器能夠和頂層方法以同樣的方式被引用:

val aReference = ::A
複製代碼

構造器和方法的惟一區別在於:構造器的首字母須要大寫。這一事實被應用於不少地方甚至是Kotlin標準庫。ListMutableList是接口,他們並無構造器,可是Kotlin的使用者們但願能夠:

List(3) { "$it" } // same as listOf("0", "1", "2")
複製代碼

這就是爲何下面的方法出如今Collections.kt :

public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T> = MutableList(size, init)

public inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> {
    val list = ArrayList<T>(size)
    repeat(size) { index -> list.add(init(index)) }
    return list
}
複製代碼

Fake constructors看起來像是構造器,用法和表現也是構造器,然而不少開發者並無意識到他們並非構造器而是頂層方法。同時Fake constructors還具備靜態工廠方法的優點:能夠返回子類型,並不須要每次調用生成新的實例;同時沒有構造器的種種限制。好比次構造器(secondary constructor)必須立刻調用主構造器(primary constructor)或者超類的構造器。當咱們使用fake constructors時還能夠推遲構造器的使用:

fun ListView(config: Config) : ListView {
    val items = … // Here we read items from config
    return ListView(items) // We call actual constructor
}
複製代碼

Primary constructor

Kotlin引入了主構造器(primary constructor)這一律念。一個Kotlin類中只能存在一個主構造器(Kotlin中稱相似Java中的構造器爲次構造器)。主構造器中的參數能夠在整個類的建立中使用:

class Student(name: String, surname: String) {
    val fullName = "$name $surname"
}
複製代碼

主構造器中的參數能夠被直接定義爲類的屬性:

class Student(val name: String, val surname: String) {
    val fullName 
        get() = "$name $surname"
}
複製代碼

當主構造器包含默認參數時,重疊構造器(Telescoping Constructor)再也不被須要。

Other ways to create an object

Kotlin中的工廠方法並非Kotlin提高實例建立的惟一方式。下篇文章咱們會討論Kotlin是如何提高builder pattern。舉個例子,容許DSL出如今對象建立過程當中:

val dialog = alertDialog {
    title = "Hey, you!"
    message = "You want to read more about Kotlin?"
    setPositiveButton { makeMoreArticlesForReader() }
    setNegativeButton { startBeingSad() }
}
複製代碼

Conclusion

在Kotlin中咱們可使用這些方式的同時,保留靜態工廠方法的優勢:

  • Companion factory method
  • Top-level function
  • Fake constructor
  • Extension factory method

一般在大多數狀況下主構造器能夠知足對象建立的需求,若是須要使用其餘的方式建立對象,能夠考慮上述的幾種方式。

相關文章
相關標籤/搜索