Last active
November 10, 2015 13:11
-
-
Save eofster/ed21660647df5aa25dc2 to your computer and use it in GitHub Desktop.
An example implementation of Null Object pattern for reference types using inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PhoneCall { | |
static let nullPhoneCall: PhoneCall = NullPhoneCall() | |
let identifier: Int | |
init(identifier: Int) { | |
self.identifier = identifier | |
} | |
func hangUp() { | |
print("Hanging up call") | |
} | |
} | |
private class NullPhoneCall: PhoneCall { | |
convenience init() { | |
self.init(identifier: 0) | |
} | |
override func hangUp() { | |
print("Not hanging up call") | |
} | |
} | |
protocol PhoneCallRegistry { | |
func callWithIdentifier(identifier: Int) -> PhoneCall | |
} | |
class PhoneCallRegistryImpl { | |
private var phoneCalls = [Int: PhoneCall]() | |
func addCall(call: PhoneCall) { | |
phoneCalls[call.identifier] = call | |
} | |
} | |
extension PhoneCallRegistryImpl: PhoneCallRegistry { | |
func callWithIdentifier(identifier: Int) -> PhoneCall { | |
if let phoneCall = phoneCalls[identifier] { | |
return phoneCall | |
} else { | |
return PhoneCall.nullPhoneCall | |
} | |
} | |
} | |
// Usage | |
let registry = PhoneCallRegistryImpl() | |
let phoneCall = PhoneCall(identifier: 1) | |
registry.addCall(phoneCall) | |
func hangUpCallWithIdentifier(identifier: Int) { | |
registry.callWithIdentifier(identifier).hangUp() | |
} | |
hangUpCallWithIdentifier(1) // Prints 'Hanging up call' | |
hangUpCallWithIdentifier(2) // Prints 'Not hanging up call' | |
let realCall = registry.callWithIdentifier(1) | |
print(realCall === PhoneCall.nullPhoneCall) // Prints 'false' | |
let nullCall = registry.callWithIdentifier(2) | |
print(nullCall === PhoneCall.nullPhoneCall) // Prints 'true' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment