Skip to content

Instantly share code, notes, and snippets.

@jbehrens94
Created January 17, 2017 11:09
Show Gist options
  • Save jbehrens94/6df122878dd84ff002d9fd7b08018d7a to your computer and use it in GitHub Desktop.
Save jbehrens94/6df122878dd84ff002d9fd7b08018d7a to your computer and use it in GitHub Desktop.
StrategyExample
import Foundation
// First define the algorithm protocol.
protocol LoadBehaviour {
func execute() -> String
}
// Define the algorithms.
// Algorithm 1
class CoreDataManager: LoadBehaviour {
func execute() -> String {
return "CoreData should be called.."
}
}
// Algorithm 2
class ApiManager: LoadBehaviour {
func execute() -> String {
return "API is safe to call, there's internet."
}
}
// The client calling LoadBehaviour.
class LoadClient: AnyObject {
// Behaviour can be changed during runtime.
var behaviour: LoadBehaviour
// Make sure the client has a default behaviour.
init(_ initialBehaviour: LoadBehaviour) {
self.behaviour = initialBehaviour
}
func load() {
print(self.behaviour.execute())
}
}
// Create the client with a default behaviour.
// We don't know whether we have internet, so first
// load data from CoreData, just to be sure.
var client = LoadClient(CoreDataManager())
client.load()
// Imagine we suddenly connect to WiFi.
client.behaviour = ApiManager()
// A few minutes later we want new data, but now we have a internet connection.
client.load()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment