I ran into a quandary last night while designing an object factory and thought I'd ask here for some guidance.
Essentially, my 'CameraFactory' returns pointers to classes based on available types such as 'FIXED' or 'FREE' (and more but I'll keep this example short). All of which inherit from CameraBase.
However, my problem is that because the CameraBase class has very limited implementation, the user needs to perform a static_cast<typeOfCameraRequested*>(returned CameraBaseDerivative*);
on the returned pointer.
I feel that by forcing the user to 'remember' to static cast the result is bad practice (I'm not using raw pointers in the actual implementation btw). But by my understanding, the only other way to create a 'neat' factory implementation would be to include an interface to all members/methods of the derivative classes in CameraBase so that the derivatives can be easily called.
Please could someone shed some light on the best approach to this issue? Should I re-design my classes? If so, what should it look like? Generics?
Thanks!
Code to consider:
Class CameraBase {
protected:
SomeDataMember mDataMember;
}
Class FreeCamera : public CameraBase {
public:
void SomeFreeCameraSpecificMethod();
}
class StaticCamera: public CameraBase {
public:
void SomeStaticCameraSpecificMethod();
}
Class CameraFactory {
public:
static BaseCamera* createCamera(CameraTypeEnum _type) {
switch (_type) {
case FREE:
return createFreeCamera();
break;
case STATIC:
return createStaticCamera();
break;
}
}
}
FreeCamera* freeCam = static_cast<FreeCamera*>(CameraFactory::createCamera(FREE));