Use the Decorator Pattern for Repository Caching and Cache Invalidation

In Swift, naturally

Steven Curtis
6 min readFeb 9


Photo by Frank Sobolewski on Unsplash

I’ve an example architecture that I’ve used for a while in these tutorials and for *other* uses. I quite like it as it conforms to the solid principles (more or less).

However, there is one thing that this architecture does not handle at all. It’s using a cache. I’ve used implementations of caching where placing the class in the code has been an afterthought and caused issues in the code, and that’s not good. Surely I can do better?

Difficulty: Beginner | Easy | Normal | Challenging | *Hard*

This article has been developed using Xcode 14.2, and Swift 5.7.2

  • There are only two hard problems in computer science. Namely they are: Naming things and Cache invalidation



SOLID: a mnemonic acronym for five design principles intended to make software designs more understandable

The issue

Repositories in this architecture work well.Looking at the diagram:

We request something from a repository and don’t need to know if the data is returned from an API endpoint or a persistent storage.

final class BrowseRepository {
private let apiService: BrowseApiServiceProtocol
private let storageService: FavouritesStorageServiceProtocol

apiService: BrowseApiServiceProtocol = BrowseApiService(),
storageService: FavouritesStorageServiceProtocol = FavouritesStorageService()
) {
self.apiService = apiService
self.storageService = storageService