Nov 4 · 1 min read
One more mechanism to consider is mixins. They allow for a separate expression of each “feature” (like feeding, petting, etc), including an implementation. A class containing all features (or any subset that you may wish to support) can then be created concisely like Dog and Cat below:
main() {
new Dog().feed("some food");
}
abstract class Pet {
void feed(String food);
void pet();
}
class Dog = Pet with FeedableDog, PettableDog;
class Cat = Pet with FeedableCat, PettableCat;
mixin FeedableDog on Pet {
void feed(String food) => print(food + "? For me?");
}
mixin FeedableCat on Pet {
void feed(String food) => print(food + "? Of course.");
}
mixin PettableDog on Pet {
void pet() => print("Yay!");
}
mixin PettableCat on Pet {
void pet() => print("I'll allow it.");
}The code above is in Dart; try it out here.