Context
Today let's do some experiment with mixin to see how this syntax and coding approach, helps to make something intuitive in coding.
I go with the context of a Warrior class, with Sword and Shield to perform a defender role. Let's examine the following codes.
class SwordMixin {
void wieldSword() {
print("Wielding sword");
}
}
class ShieldMixin {
void holdShield() {
print("Holding shield");
}
}
class Warrior with SwordMixin, ShieldMixin {
void attack() {
wieldSword();
print("Attacking enemy");
}
void defend() {
holdShield();
print("Defending against enemy");
}
}
void main() {
var warrior = Warrior();
warrior.attack();
warrior.defend();
Bonus
How about a slightly interesting example from the Archer class. Let's examine the following relationship, with Bow, arrow and quiver.
class QuiverMixin {
int arrowCount = 10;
void reloadArrows() {
arrowCount += 10;
print("Reloading arrows. Arrow count: $arrowCount");
}
}
class BowAndArrowMixin {
void drawBow() {
print("Drawing bow");
}
void fireArrow() {
print("Firing arrow");
}
}
class Archer with QuiverMixin, BowAndArrowMixin {
void attack() {
if(arrowCount > 0) {
drawBow();
fireArrow();
arrowCount--;
print("Remaining arrows: $arrowCount");
} else {
reloadArrows();
}
}
}
void main() {
var archer = Archer();
archer.attack();
archer.attack();
Conclusion
That summarized the introduction to mixin in dart, the demonstrate the intuitiveness adding "tools" to the main class.