Mixins
Dart supports mixins using the with keyword. Mixins allow you to share behavior between unrelated classes. A class that is “mixed in” must be constructed with the following rules:
- The class that is being mixed into another class must be a direct descendent of Object. It must not extend another class.
- It does not define any constructor parameters and never makes an explicit call to super().
By avoiding inheritance and class constructor requirements, mixins become candidates to append additional behavior to any class of object.
Let’s create a Bacteria class that uses a generic mixin named Printify. The Printify mixin (Example 4.24) will append the print convention that you’ve been using to allow objects to talk in their own voice. These print statements included a prefix and suffix String.
EXAMPLE 4.24
class Printify
{
String sides = '--';
void say(String output) {
print('$sides $output $sides');
}
}
class Bacteria extends Object with Printify
{
Bacteria()
{
say(".....");
}
}
main() {
Bacteria life = new Bacteria(); //prints -- ..... --
}
In the terrifying circumstance where Bacteria becomes self aware, you decide to make Bacteria a descendant of the concrete class of Being (Example 4.25). You can do this because the Printify functionality is mixed in and is in no way a member of the inheritance chain.
EXAMPLE 4.25
class Bacteria extends Being with Printify
{
Bacteria()
{
say("I am Bacteria");
}
}
main() {
Bacteria life = new Bacteria();
life.exist();
}
//Output:
//-- Init Being--
//-- I am Bacteria --
//-- I am Being and I exist--