Component pattern

Sometimes, your object hierarchy is determined by the kinds of data you're throwing around - if you have a pile of pieces of information about each customer in a database, it's obvious that you should have a Customer object. But if this is the only rule you use for deciding when to make a class, you'll often end up with enormous classes. This tends to happen for the object representing the program itself. A program tends to have a lot of things that there are only one of, and if you stick all these things in one big object then its unwieldy.

So you break up your Singleton object into components. You can do this in whatever way makes most logical sense for your program - perhaps a set of routines and data for allocating memory go in one object, and a set of routines and data for dealing with the program's main window go in another. Then you need a master object responsible for wiring all these components together. The construction of this object may be somewhat non-trivial:

In the master constructor, each of the components is constructed. However, we don't tell the components about the master yet because it's constructor is incomplete.

Once the constructor is complete, we need to loop through all the components again and "site them" (give them a pointer to the master that they can use to obtain pointers to other components they need).

Depending on how complex the interdependencies between components are, more initialization steps may be needed. The order of the components may also make a difference.

This doesn't have to be used for just the singleton - any sufficiently complex object can benefit from being broken up this way.

I looked for this pattern in the literature but didn't see it anywhere. However, it seems to be a reasonably common thing to do so I'm recording it here.

Leave a Reply