Thread: Best way to implement instance-dependent object factories?

  1. #1
    Making mistakes
    Join Date
    Dec 2008

    Best way to implement instance-dependent object factories?

    Hey, I'm working on a project incorporating runtim e modules. Several class interfaces are given which are then loaded dynamically. The library doesn't need to know about any of these classes except a few which are needed by the library. The only trouble is actually accessing these classes. Since the types are not known at compile time, the factory pattern comes to mind but it doesn't quite work as well as I'd expect (First time I really looked into it though, something might have slipped my attention).

    The whole program as a library is designed to run in so-called instances and has no global variables at all. Even though it's unlikely, each instance has its own modules and thus needs to have its own factories (or constructor methods). The way I implemented it for now is:

    class Instance {
        // ...
        // I have a macro for this stuff
        Type *(*NewType)(Instance *i, ...);
    Type *(Instance::NewType)(Instance *i, ...) = NULL;
    Then there are macros for loading a module by providing a creator function.

    This solution seems rather messy to me. Is there any way to make this work without resorting to macros and name concatenation? The catch is that different constructors may need different arguments so a template function would not work. Also it's function pointers I need, not functions.

    The ideal way would be to call

    Type *obj = instance->New<Type>(instance, args);
    but that would require template variables and is not possible, am I right?

    PS: Since modules are likely to depend on each other, is there any way to check if certain implementations (classes) are present without relying on name checking such as "if (ModuleLoaded(name)) ..."? Dynamic library are really fragile things and I don't want the whole thing to crash because module A is replaced by A' which is something else. A way to register provided classes and define their interfaces would be great although that might be a bit tedious for library development. If done right however the project itself could use the same mechanism, making it even more generic. Any ideas?
    Last edited by Brafil; 06-13-2011 at 10:53 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 01-22-2010, 10:24 PM
  2. Replies: 4
    Last Post: 11-14-2006, 11:52 AM
  3. Object reference not set to instance of an object
    By patricio2626 in forum C++ Programming
    Replies: 6
    Last Post: 10-26-2006, 08:12 AM
  4. Replies: 60
    Last Post: 12-20-2005, 11:36 PM
  5. ERRPR: Object reference not set to an instance of an object
    By blackhack in forum C++ Programming
    Replies: 1
    Last Post: 07-13-2005, 05:27 PM