Skip to content

Instantly share code, notes, and snippets.

@salmaanahmed
Last active March 22, 2021 19:54
Show Gist options
  • Save salmaanahmed/c1d26b6d3301812951bfc04abe4b3287 to your computer and use it in GitHub Desktop.
Save salmaanahmed/c1d26b6d3301812951bfc04abe4b3287 to your computer and use it in GitHub Desktop.
Repository pattern with different strategies
// The object we will be fetching from local or remote data source
struct Note {
var description: String
}
// Strategy
protocol NoteStrategy {
func getNote(completion: @escaping (Note) -> Void)
}
// Local strategy
class LocalStrategy: NoteStrategy {
func getNote(completion: @escaping (Note) -> Void) {
// fetch person from your local storage
let note = Note(description: "Note from local strategy")
completion(note)
}
// to save the note to local storage
func save(note: Note) { }
}
// Remote strategy
class RemoteStrategy: NoteStrategy {
// local strategy for updating cache
let localStrategy: LocalStrategy
func getNote(completion: @escaping (Note) -> Void) {
// fetch from backend
let note = Note(description: "Note from remote strategy")
completion(note)
// save to your local stroage for caching purposes
localStrategy.save(note: note)
}
}
// If available strategy
class IfAvailableStrategy: NoteStrategy {
// both strategies are listed here as we are dependent on both
let localStrategy: LocalStrategy
let remoteStrategy: RemoteStrategy
func getNote(completion: @escaping (Note) -> Void) {
localStrategy.getNote { note in
if note == nil {
return self.remoteStrategy.getNote(completion: completion)
}
completion(note)
}
}
}
// Repository
// You can add default value for strategy by using protocol extension
protocol NoteRepositoryProtocol {
func getNote(with strategy: NoteStrategy, completion: @escaping (Note) -> Void)
}
// Our repository 🎉
class NoteRepository: NoteRepositoryProtocol {
func getNote(with strategy: NoteStrategy, completion: @escaping (Note) -> Void) {
strategy.getNote(completion: completion)
}
}
// How to use it
var repository: NoteRepositoryProtocol
repository.getNote(with: LocalStrategy()) { note in
print(note) // prints local note
}
repository.getNote(with: RemoteStrategy()) { note in
print(note) // prints remote note
}
repository.getNote(with: IfAvailableStrategy()) { note in
print(note) // prints local note
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment