Skip to content

Instantly share code, notes, and snippets.

@pedrolemoz
Last active October 18, 2021 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrolemoz/b6135804b8028cbd98ebc2c6f9defeba to your computer and use it in GitHub Desktop.
Save pedrolemoz/b6135804b8028cbd98ebc2c6f9defeba to your computer and use it in GitHub Desktop.
Chain of resposability
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