核心思想:将创建与使用分离
定义:工厂设计模式提供了一种创建对象的方式,使得创建对象 的过程与使用对象的过程相分离。
简单来说,就是把对象的实例化过程放到了工厂中,由工厂统一管理。调用方只需依赖抽象接口,不需要关心具体的类是如何创建的。
实战演进:以数据缓存为例,看工厂模式的演进
比如数据的缓存,有内存缓存、磁盘缓存和网络缓存等方式。项目中,我们可能会使用 SharedPreferences 封装一个工具类:
kotlin
class SpUtil private constructor(context: Context) {
private val preferences: SharedPreferences =
context.applicationContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
fun putString(key: String, value: String?) = edit {
putString(key, value)
}
fun getString(key: String, defaultValue: String? = null): String? =
preferences.getString(key, defaultValue)
// 省略其余类型的 put 和 get 方法
fun contains(key: String): Boolean = preferences.contains(key)
fun remove(key: String) = edit {
remove(key)
}
fun clear() = edit {
clear()
}
private inline fun edit(block: SharedPreferences.Editor.() -> Unit) {
val editor = preferences.edit()
editor.block()
editor.apply()
}
companion object {
private const val FILE_NAME = "factory_prefs"
private var applicationContext: Context? = null
private val singleton: SpUtil by lazy {
val context = checkNotNull(applicationContext) {
"SpUtil is not initialized. Call SpUtil.init(context) first."
}
SpUtil(context)
}
fun init(context: Context) {
applicationContext = context.applicationContext
}
fun getInstance(): SpUtil = singleton
}
}
简单工厂:收敛实例化逻辑,解除调用耦合
虽然使用上没啥问题,但是一旦需要更换缓存方式时,你不得不去修改所有用到了 SpUtil 的地方。这时,就可以使用工厂模式,在不同的场景生成不同的实例来使用。
首先定义行为规范,就是定义存储产品会有哪些能力:
kotlin
interface IStorage {
fun putString(key: String, value: String?)
fun getString(key: String, defaultValue: String? = null): String?
// 省略其他类型的 put 和 get 方法
fun contains(key: String): Boolean
fun remove(key: String)
fun clear()
}
之前的 SpUtil 要实现 IStorage 接口,并将实例化的控制权交给工厂(把单例逻辑移除,方便统一管理):
名称也换成
SpStorage。
kotlin
class SpStorage internal constructor(context: Context) : IStorage {
private val preferences: SharedPreferences =
context.applicationContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
override fun putString(key: String, value: String?) = edit {
putString(key, value)
}
override fun getString(key: String, defaultValue: String?): String? =
preferences.getString(key, defaultValue)
// 省略其余类型的 put 和 get 方法
override fun contains(key: String): Boolean = preferences.contains(key)
override fun remove(key: String) = edit {
remove(key)
}
override fun clear() = edit {
clear()
}
private inline fun edit(block: SharedPreferences.Editor.() -> Unit) {
val editor = preferences.edit()
editor.block()
editor.apply()
}
companion object {
private const val FILE_NAME = "factory_prefs"
}
}
再补充一个内存缓存的实现:
kotlin
class MemoryStorage internal constructor() : IStorage {
private val cache = mutableMapOf<String, String?>()
override fun putString(key: String, value: String?) {
cache[key] = value
}
override fun getString(key: String, defaultValue: String?): String? =
cache[key] ?: defaultValue
override fun contains(key: String): Boolean = cache.containsKey(key)
override fun remove(key: String) {
cache.remove(key)
}
override fun clear() {
cache.clear()
}
}
然后创建工厂,它会根据存储类型返回不同的产品:
kotlin
enum class StorageType {
SP,
MEMORY
}
object StorageFactory {
private val memoryStorage by lazy { MemoryStorage() }
fun create(context: Context, type: StorageType): IStorage =
when (type) {
StorageType.SP -> SpStorage(context)
StorageType.MEMORY -> memoryStorage
}
}
这里每次都返回同一个 memoryStorage 实例,是为了避免每次调用时都拿到空 Map。工厂模式只是管理了对象的创建,但并没有限制每次都必须创建新对象,实际项目中,工厂完全可以返回单例或复用实例。
调用方只需依赖 IStorage 接口:
kotlin
val storage: IStorage = StorageFactory.create(context, StorageType.SP)
storage.putString("token", "abc123")
val token = storage.getString("token")
这就是简单工厂(严格来说,它不属于 GoF 设计模式,可以认为是后两种模式的简化版本)。
经过封装,将调用和具体实现解耦了,可以随时切换缓存的类型。而且对外部隐藏了创建细节。
工厂方法:抽象工厂本身,拥抱开闭原则
在简单工厂中,如果要新增产品(比如磁盘缓存),必须要改动原有的代码:往枚举中新增枚举常量,并在 create 方法的 when 分支里增加新产品的创建逻辑,这违背了开闭原则(对扩展开放,对修改关闭)。
如果要提升扩展性,可以使用工厂方法:将工厂本身也抽象化,把具体的创建过程延迟到子类去实现,一个工厂对应一个产品的创建。
首先新增工厂接口:
kotlin
interface IStorageFactory {
fun create(): IStorage
}
分别创建 SpStorage 和 MemoryStorage 的工厂实现,Context 通过具体工厂的构造函数传入:
kotlin
class SpStorageFactory(context: Context) : IStorageFactory {
private val appContext = context.applicationContext
override fun create(): IStorage = SpStorage(appContext)
}
class MemoryStorageFactory : IStorageFactory {
private val storage by lazy { MemoryStorage() }
override fun create(): IStorage = storage
}
此时,假如要新增一个磁盘缓存产品,无需改动之前已有的代码,只需增加产品和对应的工厂实现即可:
kotlin
class DiskStorage internal constructor() : IStorage {
// 省略具体磁盘读写实现
}
class DiskStorageFactory : IStorageFactory {
override fun create(): IStorage = DiskStorage()
}
调用方只需依赖抽象工厂,切换存储方式只需替换具体工厂即可:
kotlin
val factory: IStorageFactory = SpStorageFactory(context)
val storage: IStorage = factory.create()
storage.putString("token", "abc123")
不过,这种方式也有问题,随着产品类型不断增加,各个产品的工厂实现类会越来越多,容易导致类膨胀。
抽象工厂:成套生产,约束产品族一致性
抽象工厂用于解决产品族的创建问题,保证创建出的一组相关产品一定是配套的。
注意,抽象工厂只是三种工厂模式的一种,并不是工厂方法的更优解。包括工厂方法,也不一定优于简单工厂。
比如除了存储产品外,还多了存储事务产品:
kotlin
/**
* 存储事务接口
*/
interface IStorageTransaction {
fun putString(key: String, value: String?): IStorageTransaction
fun remove(key: String): IStorageTransaction
fun clear(): IStorageTransaction
fun commit()
}
工厂抽象要新增对应的方法:
kotlin
interface IStorageFactory {
fun createStorage(): IStorage
fun createTransaction(): IStorageTransaction
}
具有事务的存储实现,以 MemoryStorageTransaction 为例:
kotlin
class MemoryStorageTransaction internal constructor(
private val cache: MutableMap<String, String?>,
) : IStorageTransaction {
private val updates = mutableMapOf<String, String?>()
private val removals = mutableSetOf<String>()
private var clearRequested = false
override fun putString(key: String, value: String?): IStorageTransaction {
removals.remove(key)
updates[key] = value
return this
}
override fun remove(key: String): IStorageTransaction {
updates.remove(key)
removals.add(key)
return this
}
override fun clear(): IStorageTransaction {
updates.clear()
removals.clear()
clearRequested = true
return this
}
override fun commit() {
if (clearRequested) {
cache.clear()
}
removals.forEach(cache::remove)
cache.putAll(updates)
updates.clear()
removals.clear()
clearRequested = false
}
}
需要调整一下 MemoryStorage,将缓存移至构造函数,这样它和事务实现才能共享同一份缓存:
kotlin
class MemoryStorage internal constructor(
private val cache: MutableMap<String, String?>,
) : IStorage {
// ...
}
最后具体工厂也要修改:
kotlin
class MemoryStorageFactory : IStorageFactory {
private val cache = mutableMapOf<String, String?>()
override fun createStorage(): IStorage = MemoryStorage(cache)
override fun createTransaction(): IStorageTransaction =
MemoryStorageTransaction(cache)
}
调用方从同一个工厂获取的产品,一定是配套的(比如 MemoryStorage + MemoryStorageTransaction,或者 SpStorage + SpStorageTransaction):
kotlin
val factory: IStorageFactory = MemoryStorageFactory()
val storage = factory.createStorage()
val transaction = factory.createTransaction()
transaction
.putString("token", "abc123")
.putString("user", "zhangsan")
.commit()
val token = storage.getString("token")
抽象工厂也有缺点:新增一整套产品族非常方便,但要在现有的产品族中新增一种产品,就必须修改工厂接口,以及它所有的具体子类,改动较大。
选型指南:三种模式怎么用
怎么选呢?
优先选择简单工厂 ,当发现产品变多,而且变动频繁时,可以使用工厂方法 。明显存在多套配套使用的组件时,才考虑抽象工厂。