I have a Class (MyFactory) which produces objects of type A. (myFactory will be an instance)
I want to allow users to extends the class A (to a Class B, for example), and override virtual methods of A.
For example, users who don’t want to extend A :
A* myObject = myFactoryInstance.createObject();
And my current trick for users which extends A with B :
B* myObjectPrepare = new B()
myFactoryInstance.setNextObject( myObjectPrepare );
A* myObject = myFactoryInstance.createObject(); // Will look for a "next_object"
/* Here, myObject (which is myObjectPrepare modified by createObject)
methods will dynamically link to B class methods. */
My goal is to facilitate this operation.
.
I tried :
template <class T>
void MyFactory::set_requests_class() {
new T();
/* I don't want an instance, now. Just memorize class type
at compilation time, and make instances of T along exec
*/
}
(usage : set_requests_class(); Problem : I don’t want to produce instance)
That could be a solution :
myFactoryInstance.createObject<YourObjectTypeHere>();
But I don’t want to make the template parameter mandatory (default parameter for an attribute is only possible since c++11) : I want to keep it very simple for users who don’t want to extends A.
I CAN’T modify “createObject” signature, for the same reason.
(My future trick will be to instanciate the B object, keep it as attribute and clone it for new instances)
Thank you in advance (any suggestion will be appreciated)
The easiest way is to just overload
createObject. See this example:And if you need to keep your design, where you set the type to create before you actually create the objects, then you can do it using a secondary factory like below. It’s not a very nice design though; basically the factory class now basically just acts as a wrapper that casts the result. Seems like there’s a better design from the outside.