A couple options:
Rethink your usage
An abstract factory is useful if it separates the user of the factory from how the exact type is produced. The abstract factory doesn't have any restrictions on what it produces, just that it is abstract. It can return a non-abstract type, or an abstract type that isn't at the very base of your inheritance hierarchy.
If code that uses the factory already can get different sets of data to call the factory with, then the code using the factory already has some knowledge of the type that comes out of it.
Here are some options to think about:
- Provide multiple abstract factory types, with one
Create
method each, such as a GrenadeFactory
and a BulletFactory
- Provide multiple methods on a single abstract factory type, such as
CreateBullet
and CreateGrenade
- Stop using abstract factories. This is a good option if you don't really need abstract construction, and just need abstract types.
Remember that you can still pass a derived type (Bullet
) to a method taking a base type (say, Entity
or Projectile
).
Double dispatch
If you're really dead set on combining abstract factories with abstract parameters, then you may want to look into double dispatch, or the Visitor Pattern. The key here is that you're trying to get two different virtual methods to be combined with each other, and get a unique combination of behavior based on those two derived types.
This would require you to create base and derived types for your parameters, so you couldn't pass simple types (like int, string, etc) without creating a custom parameter structure that derived from a base Parameters
type.
It also requires a lot of extra code to implement the Visitor pattern.
RTTI
You could use the C++ Run-Time Type Information feature.
Using dynamic_cast
, you can cast a base type to a derived type. You could do this in the factory implementation to cast your base parameter type to your specific parameter type.
Like double-dispatch, this would also require you to create a type hierarchy for parameters, but would require less code to stitch them together (wouldn't require the visitor pattern).
This option would tightly couple your factory implementation to a parameter structure implementation, though.
Property bag
You can also use a string
-> some type
dictionary (string
-> boost::any
, for example). This is called a property bag. It loses you a lot of compile time type safety, though, because you're basically looking everything up by string value. I don't really recommend it.