I l@ve RuBoard Previous Section Next Section

8.8 Using Object Factories with Other Generic Components

Chapter 6 introduced the SingletonHolder class, which was designed to provide specific services to your classes. Because of the global nature of factories, it is natural to use Factory with SingletonHolder. They are very easy to combine by using typedef. For instance:



typedef SingletonHolder< Factory<Shape, std::string> > ShapeFactory;


Of course, you can add arguments to either SingletonHolder or Factory to choose different trade-offs and design decisions, but it's all in one place. From now on, you can isolate a bunch of important design choices in one place and use ShapeFactory throughout the code. Within the simple type definition just shown, you can select the way the factory works and the way the singleton works, thus exploiting all the combinations between the two. With a single line of declarative code, you direct the compiler to generate the right code for you and nothing more, just as at runtime you'd call a function with various parameters to perform some action in different ways. Because in our case it all happens at compile time, the emphasis is more on design decisions than on runtime behavior. Of course, runtime behavior is affected as well, but in a more global and subtle way. By writing "regular" code, you specify what's going to happen at runtime. When you write a type definition such as the one above, you specify what's going to happen during compile time—in fact, you kind of call code-generation functions at compile time, passing arguments to them.

As alluded to in the beginning of this chapter, an interesting combination is to use Factory with Functor:



typedef SingletonHolder


<


   Factory


   <


      Shape, std::string, Functor<Shape*>


   >


>


ShapeFactory;


This gives you great flexibility in creating objects, by leveraging the power of Functor (for which implementation we took great pains in Chapter 5). You can now create Shapes in almost any way imaginable by registering various Functors with the Factory, and the whole thing is a Singleton.

    I l@ve RuBoard Previous Section Next Section