Skip to content

Instantly share code, notes, and snippets.

@FrancescoJo
Created June 17, 2019 13:38
Show Gist options
  • Save FrancescoJo/98c0eaa9f79903ccc4d1525f94ee54b2 to your computer and use it in GitHub Desktop.
Save FrancescoJo/98c0eaa9f79903ccc4d1525f94ee54b2 to your computer and use it in GitHub Desktop.
An example to demonstrate animal classification system in Dart 2.x.
class Animal { }
class Reptile extends Animal { }
class Bird extends Animal { }
mixin MobileLife {
// We don't need to implement _move on every classes using this mixin, since mixin can include state.
var _distance = 0.0;
void _move(double displacement) {
_distance += displacement;
print("I moved ${_getDistance()} metres.");
}
double _getDistance() => _distance;
}
mixin Swimmer on MobileLife {
void swim() {
super._move(_getSwimDistance());
}
double _getSwimDistance() => 0.0;
}
mixin Walker on MobileLife {
void walk() {
super._move(_getWalkDistance());
}
double _getWalkDistance() => 0.0;
}
class Duck extends Bird with MobileLife, Walker, Swimmer {
@override
double _getWalkDistance() => 0.05;
@override
double _getSwimDistance() => 0.1;
}
class Turtle extends Reptile with MobileLife, Walker, Swimmer {
@override
double _getSwimDistance() => 0.5;
// Turtles are so slow to move 1 metre for 10 times of move command
var walkTimes = 0;
void walk() {
walkTimes++;
if (walkTimes % 10 == 0) {
super._move(0.001);
}
super.walk();
}
}
void main() {
print("Duck says:");
final duck = Duck();
duck.walk();
duck.swim();
print("Turtle says:");
final turtle = Turtle();
turtle.swim();
for(var i = 0; i < 10; i++) {
turtle.walk();
}
}
/*
* Result:
* Duck says:
*
* I moved 0.05 metres.
* I moved 0.15000000000000002 metres.
*
* Turtle says:
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.501 metres.
* I moved 0.501 metres.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment