C++ – Is there something like a polymorphic Singleton

Architecturecdesign-patternssingleton

I have a resource loader object that loads objects from the disk or from a ZIP archive, depending on the platform.

It has state (e.g. the path to the directory or the ZIP archive, and possibly some caching in the future), so it needs to be a single instance.

So normally, a Singleton would do. But my problem is that this resource loader has multiple implementations, of which one is chosen at initialisation. So turning the resource loader into a Singleton won't do.

All I can think of is to have a Singleton that holds a reference to the single resource loader. But isn't there a nicer pattern for this?

Best Answer

What you want sounds like a good case for the Factory pattern. You would write something like:

class LoaderFactory {
  public Loader getLoader() {
    if (environment1) return ZipLoader.getInstance();
    else if (environment2) return DiskLoader.getInstance();
    else return SomeOtherLoader.getInstance();
  }
}

Each type of Loader class is a singleton, and each should implement the Loader interface. Your LoaderFactory performs the logic that determines which type is appropriate to return.

Related Topic