Factory Patterns in Practice: Rebuilding an Android Cache from Simple to Abstract
Core Idea: Separating Creation from Use
Definition: The factory design pattern provides a way to create objects, separating the process of creating objects from the process of using them.
Simply put, it moves object instantiation into a factory, which manages it centrally. Callers only depend on an abstract interface and don't need to know how concrete classes are created.
Practical Evolution: From Data Cache to Factory Patterns
Take data caching, for example. There are memory cache, disk cache, and network cache. In a project, we might wrap SharedPreferences in a utility class:
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)
// Other put and get methods omitted
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
}
}
Although this works fine, once you need to switch cache types, you have to modify every place that uses SpUtil. That's where the factory pattern comes in: use it to create instances for different scenarios.
First define the behavior contract, the capabilities a storage product should have:
interface IStorage {
fun putString(key: String, value: String?)
fun getString(key: String, defaultValue: String? = null): String?
// Other put and get methods omitted
fun contains(key: String): Boolean
fun remove(key: String)
fun clear()
}
The previous SpUtil should implement IStorage and hand over instantiation control to the factory (remove the singleton logic for unified management):
The name is also changed to
SpStorage.
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)
// Other put and get methods omitted
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"
}
}
Then a memory cache implementation:
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()
}
}
Then create a factory that returns different products based on storage type:
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
}
}
Returning the same memoryStorage instance each time avoids getting an empty Map on every call. The factory pattern only manages object creation; it doesn't force a new object every time. In real projects, a factory can return singletons or reuse instances.
Callers only need to depend on the IStorage interface:
val storage: IStorage = StorageFactory.create(context, StorageType.SP)
storage.putString("token", "abc123")
val token = storage.getString("token")
This is the simple factory (strictly speaking, it's not one of the GoF design patterns; you can think of it as a simplified version of the latter two patterns).
After this encapsulation, calls and concrete implementations are decoupled, and you can switch cache types anytime. Creation details are hidden from the outside.
Factory Method: Abstract the Factory Itself and Embrace the Open-Closed Principle
In the simple factory, to add a new product (such as disk cache), you must modify existing code: add an enum constant and add the new product's creation logic in the create method's when branch. This violates the open-closed principle (open for extension, closed for modification).
To improve extensibility, use the factory method: abstract the factory itself and defer the concrete creation process to subclasses. One factory handles the creation of one product.
First add a factory interface:
interface IStorageFactory {
fun create(): IStorage
}
Create factory implementations for SpStorage and MemoryStorage, passing Context through the concrete factory's constructor:
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
}
At this point, if you want to add a disk cache product, you don't need to change existing code. Just add the product and its factory implementation:
class DiskStorage internal constructor() : IStorage {
// Disk read/write implementation omitted
}
class DiskStorageFactory : IStorageFactory {
override fun create(): IStorage = DiskStorage()
}
Callers only need to depend on the abstract factory. Switching storage methods is just swapping the concrete factory:
val factory: IStorageFactory = SpStorageFactory(context)
val storage: IStorage = factory.create()
storage.putString("token", "abc123")
But this approach also has a problem: as product types increase, the number of factory implementation classes grows and can lead to class bloat.
Abstract Factory: Produce Sets and Enforce Product Family Consistency
The abstract factory solves the creation problem of product families, ensuring that a group of related products are always compatible.
Note: the abstract factory is just one of the three factory patterns, not a better solution than the factory method. Even the factory method is not necessarily better than the simple factory.
For example, besides storage products, there is now a storage transaction product:
/**
* Storage transaction interface
*/
interface IStorageTransaction {
fun putString(key: String, value: String?): IStorageTransaction
fun remove(key: String): IStorageTransaction
fun clear(): IStorageTransaction
fun commit()
}
The abstract factory needs new methods:
interface IStorageFactory {
fun createStorage(): IStorage
fun createTransaction(): IStorageTransaction
}
A transaction-capable storage implementation, using MemoryStorageTransaction as an example:
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
}
}
You need to adjust MemoryStorage to move the cache into the constructor so that the storage and transaction implementations share the same cache:
class MemoryStorage internal constructor(
private val cache: MutableMap<String, String?>,
) : IStorage {
// ...
}
Finally, the concrete factory also changes:
class MemoryStorageFactory : IStorageFactory {
private val cache = mutableMapOf<String, String?>()
override fun createStorage(): IStorage = MemoryStorage(cache)
override fun createTransaction(): IStorageTransaction =
MemoryStorageTransaction(cache)
}
Products obtained from the same factory are guaranteed to be compatible (for example, MemoryStorage + MemoryStorageTransaction, or SpStorage + SpStorageTransaction):
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")
The abstract factory also has drawbacks: adding a whole new product family is convenient, but to add a new product to an existing family, you must modify the factory interface and all its concrete subclasses, which is a larger change.
Selection Guide: How to Use the Three Patterns
How to choose?
Prefer the simple factory. When you find that products are increasing and changing frequently, use the factory method. Only consider the abstract factory when there are clearly multiple sets of components that are used together.