[c9bc2b7] | 1 | /*
|
---|
| 2 | * Creator_impl.hpp
|
---|
| 3 | *
|
---|
| 4 | * Created on: Jan 3, 2011
|
---|
| 5 | * Author: heber
|
---|
| 6 | */
|
---|
| 7 |
|
---|
| 8 | #ifndef CREATOR_IMPL_HPP_
|
---|
| 9 | #define CREATOR_IMPL_HPP_
|
---|
| 10 |
|
---|
| 11 | // include config.h
|
---|
| 12 | #ifdef HAVE_CONFIG_H
|
---|
| 13 | #include <config.h>
|
---|
| 14 | #endif
|
---|
| 15 |
|
---|
| 16 |
|
---|
| 17 | /** This class wraps another one and implements a create() function for it.
|
---|
| 18 | *
|
---|
| 19 | * This pattern is sometimes called 'type erasure': we want to present
|
---|
| 20 | * the user with a abstract interface only (name) but in
|
---|
| 21 | * order to create a copy (such that handed out instances are independent from
|
---|
| 22 | * one another) we have to know about the type of underlying (complex) class.
|
---|
| 23 | *
|
---|
| 24 | * Hence, we create this templated creator class (name##_Creator), which has an
|
---|
| 25 | * abstract creation interface (I##name##_Creator).
|
---|
| 26 | *
|
---|
| 27 | * This pattern is e.g. very useful when multiple (proto)types have to be
|
---|
| 28 | * stored in the table of a factory. Factories can serve only a general
|
---|
| 29 | * (abstract) type and not the specific one due to a necessary general function
|
---|
| 30 | * signature.
|
---|
| 31 | *
|
---|
| 32 | * <h1> Howto </h1>
|
---|
| 33 | *
|
---|
| 34 | * Wrap the classes to instantiate by the factory in this creator
|
---|
| 35 | * pattern. The factory in its tables only stores the abstract creation
|
---|
| 36 | * interface (I##name##_Creator). Let the factory call create() when it has to
|
---|
| 37 | * produce an instance, which is passed through to the templated creation class
|
---|
| 38 | * (name##_Creator), dealing out the copy.
|
---|
| 39 | *
|
---|
| 40 | * <h1>Best Practice </h1>
|
---|
| 41 | *
|
---|
| 42 | * NOTE: It is best-practice to place the call to CONSTRUCT_CREATOR in its
|
---|
| 43 | * own header file and include this file only. Otherwise, one might get
|
---|
| 44 | * redefinition errors.
|
---|
| 45 | */
|
---|
| 46 | #define CONSTRUCT_CREATOR(name) \
|
---|
| 47 | class name; \
|
---|
| 48 | struct I##name##_Creator \
|
---|
| 49 | { \
|
---|
| 50 | virtual ~I##name##_Creator() {}; \
|
---|
| 51 | virtual name * create() const =0; \
|
---|
| 52 | }; \
|
---|
| 53 | template <class T> \
|
---|
| 54 | struct name##_Creator : public I##name##_Creator \
|
---|
| 55 | { \
|
---|
| 56 | virtual name * create() const { \
|
---|
| 57 | return new T(); \
|
---|
| 58 | }; \
|
---|
| 59 | };
|
---|
| 60 |
|
---|
| 61 |
|
---|
| 62 | #endif /* CREATOR_IMPL_HPP_ */
|
---|