Factory Patterns in Practice: Rebuilding an Android Cache from Simple to Abstract
Design pattern choices carry real maintenance costs; this cache example shows exactly when each factory pattern pays off and when it becomes overkill.
The factory pattern moves the work of instantiating objects behind an abstraction, so callers depend on an interface instead of concrete classes. An Android storage cache makes the case concrete: the initial SpUtil wraps SharedPreferences and exposes a singleton, forcing every consumer to know that concrete type. Switching cache strategies means touching every call site. A simple factory adds an IStorage interface and a StorageFactory that returns either a SharedPreferences-backed SpStorage or an in-memory MemoryStorage; callers only need IStorage and a StorageType enum. The factory can reuse a singleton instance, as the MemoryStorage lazy singleton does, so it doesn't force a fresh object per call.
The simple factory violates the open-closed principle when a new storage type arrives: you edit the enum and the when branch. The factory method pattern abstracts the factory itself with an IStorageFactory interface, letting each product have its own factory and deferring creation to subclasses. Adding DiskStorage means adding DiskStorage and DiskStorageFactory with no changes to existing code, but factory classes multiply as products grow. The abstract factory handles product families: storage plus storage transaction, with a shared cache. It guarantees compatible products from the same factory, but extending an existing family requires modifying the factory interface and every concrete subclass. The selection guidance is pragmatic: start with a simple factory, move to factory method as product variety grows, reserve abstract factory for clearly matched product sets.
The advice to prefer the simple factory until change pressure emerges runs against the common habit of applying the most elaborate pattern upfront.
Factories and singletons coexist: the factory returns a lazy singleton for memory storage, showing that creation management doesn't mean a new object every call.
The real gain of the abstract factory is consistency, not flexibility; the example shows how a transaction and a storage share the same cache only when created from the same factory.