Show Lecture.Mixins as a slide show.
CS253 Mixins
🍨
Origin
The name “mixin” comes from adding various treats to ice cream,
such as the McFlurry, Blizzard, or
the ground-breaking research at Cold Stone Creamery.
Is-A
We know the is-a relationship, which comes from class inheritance:
class Dog {
public:
virtual const char * drink() { return "Lap lap lap."; }
virtual const char * bark() { return "Woof!"; }
virtual ~Dog() = default;
};
class Chihuahua : public Dog {
public:
virtual const char * bark() { return "¡Yip!"; }
};
Dog *koko = new Chihuahua;
cout << koko->drink() << '\n' << koko->bark();
delete koko;
Lap lap lap.
¡Yip!
Mixins
- Mixins also use inheritance, and could certainly be considered
an is-a relationship, but don’t think about it that way.
- Focus on the base class providing methods
to the derived class.
class PowerRing {
public:
auto zap() { return "green beam"; }
auto fly() { return "up, up, and … ?"; }
};
class GreenLantern : public PowerRing { };
GreenLantern john_stewart;
cout << john_stewart.zap();
green beam
- Don’t think of John as being a power ring.
Instead, he uses the abilities that the power ring gives him.
Usefulness
- Beginning programmers put everything in one giant main().
- Experienced programmers break up a big program into several functions.
- This helps to make each individual function manageable.
- Beginning O-O programmers put everything into
one giant class.
- Experienced programmers, break up a big class into several classes.
- This helps to make each individual class manageable.
- Classes can be combined in several ways. Has-a and is-a are two
common methods. Mixins are a certain type of is-a.