Last active
August 23, 2018 07:23
-
-
Save dimagimburg/4b81242b6222e4281de484fecf1b3f8b to your computer and use it in GitHub Desktop.
An example of simple implementation of Strategy Pattern to validators
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
// for quick demonstation and run paste this code in here: http://online.swiftplayground.run | |
import Foundation | |
class ValidatorContext { | |
var strategy: ValidatorStrategy | |
var isValid: Bool { | |
get { | |
return self.validationResult?.valid ?? false | |
} | |
set {} | |
} | |
var msg: String { | |
get { | |
return self.validationResult?.msg ?? "" | |
} | |
set {} | |
} | |
private var validationResult: ValidationResult? { | |
didSet { | |
if let validationResult = validationResult { | |
self.isValid = validationResult.valid | |
self.msg = validationResult.msg | |
} | |
} | |
} | |
init() { | |
self.strategy = DefaultValidatorStrategy() | |
} | |
init(strategy: ValidatorStrategy) { | |
self.strategy = strategy | |
} | |
func validate(value: Any) -> ValidatorContext { | |
self.validationResult = self.strategy.validate(value: value) | |
return self | |
} | |
} | |
protocol ValidatorStrategy { | |
func validate(value: Any) -> ValidationResult | |
} | |
class DefaultValidatorStrategy: ValidatorStrategy { | |
func validate(value: Any) -> ValidationResult { | |
return ValidationResult(valid: false, msg: "") | |
} | |
} | |
struct ValidationResult { | |
let valid: Bool | |
let msg: String | |
} | |
class PasswordValidatorStrategy { | |
} | |
class EmailValidatorStrategy: ValidatorStrategy { | |
func validate(value: Any) -> ValidationResult { | |
var valid = true | |
var msg = "" | |
if let value = value as? String { | |
if value.range(of:"@") == nil { | |
valid = false | |
msg = "Not valid email" | |
} | |
} else { | |
valid = false | |
msg = "Value is not of type String" | |
} | |
return ValidationResult(valid: valid, msg: msg) | |
} | |
} | |
// CLIENT AND TESTS | |
let myValidPassword = "Gasdb$%" | |
let myValidEmail = "test@example.com" | |
var context = ValidatorContext().validate(value: myValidPassword) | |
print("valid: ", context.isValid) | |
print("msg: ", context.msg) | |
context.strategy = EmailValidatorStrategy() | |
context.validate(value: myValidPassword) | |
print("valid: ", context.isValid) | |
print("msg: ", context.msg) | |
context.validate(value: myValidEmail) | |
print("valid: ", context.isValid) | |
print("msg: ", context.msg) | |
context.validate(value: 666) | |
print("valid: ", context.isValid) | |
print("msg: ", context.msg) | |
context.msg = "HELLO WORLD" // ignore setter | |
print("msg: ", context.msg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment