Here are some examples of
MixIns for
CeePlusPlus
In the context of C++ [
CeePlusPlus] the term mixin is usually used to match
BjarneStroustrup's definition:
-
- A class that provides some - but not all - of the implementation for a virtual base class is often called a "mixin".
You can for example have a virtual abstract base class that defines the interfaces for the import and export of values and a flock of derived classes that implement different means to either export or import, but not both. Then you can combine these second-layer classes to form different concrete classes.
I believe that it's possible to
MixIn from above (parent classes) or
MixIn from below (
AbstractSubclasses). The above example shows an example of
MixIn from the parent classes through
MultipleInheritance. For
CeePlusPlus,
AbstractSubclasses written by
UsingTemplates.
Examples for MixIn through AbstractSubclass
The following code implements the
SingletonPattern
template<class SingletonClass>
class Singleton : public SingletonClass
{
public:
/** Singleton creation function */
static Singleton & instance()
{
if(_instance.get() == NULL)
{
_instance = auto_ptr<Singleton<SingletonClass> >(new Singleton);
assert(_instance.get() != NULL);
}
return *_instance;
}
protected:
/** Singleton instance holder */
static auto_ptr<Singleton<SingletonClass> > _instance;
};
/** static instance definition */
template<class SingletonClass> auto_ptr<Singleton<SingletonClass> > Singleton<SingletonClass>::_instance;
If we have a class called M
yClass:
class MyClass
{
public:
virtual void bar();
virtual ~MyClass();
protected:
MyClass();
};
The constructor can either be public or protected depending on the need. A protected constructor can ensure that the class will only be possible to be constructed by subclasses in this case the Singleton
MixIn.
The
MixIn can be used like:
void foo()
{
Singleton<MyClass>::instance().bar();
}
or
class SingletonMyClass : public Singleton<MyClass>
{
};
void foo()
{
SingletonMyClass::instance().bar();
}
The STL's auto_ptr is used to ensure proper destruction. In this example, the abstract method this
MixIn requires from the parent class is the default constructor. The disadvantage is that it is harder to pass parameters through constructor, but the advantage is
OnceAndOnlyOnce because any class can be a singleton by mixing in the
AbstractSubclass without rewriting the same code.