TK.
TK.

Reputation: 47873

VB6 Is it possible to implement the Singleton design pattern?

Within VB6 is it possible to implement the Singleton design pattern?

Currently the legacy system I work on has a large about of IO performed by multiple instances of a particular class. It is desirable to clean up all these instances and have the IO performed by one instance only. This would allow us to add meaningful logging and monitoring to the IO routines.

Upvotes: 4

Views: 2469

Answers (2)

Deanna
Deanna

Reputation: 24253

It's easy enough to only create and use one instance of an object. How you do it depends on your code what it does and where it's called from.

In one process, you can just have a single variable in a global module with an instance, maybe with a factory function that creates it on first use.

If it's shared by multiple process, it complicates things, but can be done with an ActiveX EXE and the Running Object Table.

Upvotes: 2

tcarvin
tcarvin

Reputation: 10855

There are so many ways to do this, and it depends if this is a multi-project application with different dlls or a single project.

If it is single project and there is a large amount of code that you are worrying about chaning/breaking then I suggest the following:

  1. Given a class clsIOProvider that is instantiated all over the place, create a module modIOProvider in the same project.
  2. For each method / property defined in clsIOProvider, create the same set of methods in modIOProvider.
  3. The implementation of those methods, as well as the instance data of the class, should be cloned from clsIOProvider to modIOProvider.
  4. All methods and properties in clsIOProvider should be chnaged to forward to the implementation in modIOProvider. The class should no longer have an instance data.
  5. (Optional) If the class requires the use of the constructor and destructor (Initialize/Terminate), forward those to modIOProvider as well. Add a single instnace counter within modIOProvider to track the number of instances. Run your initialzation code when the instance counter goes from 0 to 1, and your termination code when the instance counter goes from 1 to 0.

The advantage of this is that you do not have to change the coe in the scores of places that are utilizeing the clsIOProvider class. They are happily unaware that the object is now effectively a singleton.

If coding a proejct from scratch I would do this a bit differently, but as a refactoring appraoch wahat I've outlined should work well.

Upvotes: 3

Related Questions