GoF design patterns in Android
Interviews reward showing where you meet each pattern in Android, not reciting definitions:
- Singleton — one instance: Kotlin's
object,@Singletonin DI. Retrofit and Room instances. - Builder — step-by-step construction of complex objects:
OkHttpClient.Builder(),NotificationCompat.Builder,AlertDialog.Builder. Kotlin's named/default arguments often replace it. - Factory — hiding creation logic:
ViewModelProvider.Factory,Fragment.instantiate. - Observer — subscribing to events: LiveData/Flow, listeners, BroadcastReceiver.
- Adapter — translating incompatible interfaces:
RecyclerView.Adapter(data ↔ view holders). - Facade — a simple face over a complex subsystem: the Repository pattern is exactly this.
- Strategy — swappable algorithms: interceptor chains, image loader configurations.
- Decorator — layering behavior on top: OkHttp interceptors "decorate" the request.
| Pattern | Android example | One-line essence |
|---|---|---|
| Singleton | `object`, the Retrofit instance | One instance, global access |
| Builder | OkHttpClient.Builder | Assemble a complex object stepwise |
| Observer | Flow/LiveData collect/observe | Subscribe to changes |
| Adapter | RecyclerView.Adapter | Bridge two incompatible interfaces |
| Facade | Repository | A simple door to complexity |
| Decorator | OkHttp Interceptor | Extend by wrapping |
Singleton criticism gets asked too: global mutable state, hidden dependencies, untestability. The modern answer: singletons should be managed as DI scopes (@Singleton), not as stateful objects. To "is Singleton an antipattern?" answer with balance: the usage, not the pattern, is the problem — an object for stateless utils is fine, global mutable state is not.
🛠 Practice task
Pattern hunt in the Android SDK: pick 6 patterns and find a real example of each in the SDK (jump to source with Ctrl+B).
OkHttpClient.Builder,RecyclerView.Adapter,ViewModelProvider.Factory, Flow/LiveData, Repository, Interceptor.- Then apply one Strategy in your own project: an interface + two implementations + DI selection.
Done when: for each pattern you can say why that pattern belongs in that spot.
📚 Sources and documentation
- OkHttp Interceptors (Decorator/Strategy in the wild)officiallysine.dev
- ViewModelProvider.Factoryofficialdeveloper.android.com