Last active
October 18, 2021 13:34
-
-
Save pedrolemoz/b6135804b8028cbd98ebc2c6f9defeba to your computer and use it in GitHub Desktop.
Chain of resposability
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
abstract class Validator { | |
final Validator? nextValidator; | |
Validator([this.nextValidator]); | |
bool call(int value); | |
} | |
class Class1 implements Validator { | |
@override | |
final Validator? nextValidator; | |
Class1([this.nextValidator]); | |
@override | |
bool call(int value) { | |
if (nextValidator != null) { | |
if (value >= 10) { | |
return nextValidator!(value); | |
} | |
throw Exception('Error on class 1 with value $value'); | |
} | |
return value >= 10 | |
? true | |
: throw Exception('Error on class 1 with value $value'); | |
} | |
} | |
class Class2 implements Validator { | |
@override | |
final Validator? nextValidator; | |
Class2([this.nextValidator]); | |
@override | |
bool call(int value) { | |
if (nextValidator != null) { | |
if (value >= 100) { | |
return nextValidator!(value); | |
} | |
throw Exception('Error on class 2 with value $value'); | |
} | |
return value >= 100 | |
? true | |
: throw Exception('Error on class 2 with value $value'); | |
} | |
} | |
class Class3 implements Validator { | |
@override | |
final Validator? nextValidator; | |
Class3([this.nextValidator]); | |
@override | |
bool call(int value) { | |
if (nextValidator != null) { | |
if (value >= 1000) { | |
return nextValidator!(value); | |
} | |
throw Exception('Error on class 3 with value $value'); | |
} | |
return value >= 1000 | |
? true | |
: throw Exception('Error on class 3 with value $value'); | |
} | |
} | |
void main() { | |
const value = 2000; | |
final v3 = Class3(); | |
final v2 = Class2(v3); | |
final v1 = Class1(v2); | |
print(v1(value)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment