O'Reilly logo

Prefactoring by Ken Pugh

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.4. Indirection

An oft-quoted rule of computer science is "Most problems in computer science can be solved by another level of indirection ." One might complain that too many levels of indirection can create maintenance problems. But like many other design facets, taking out indirection is often easier than adding it later. The Factory pattern (see Design Patterns by Erich Gamma et al.) is a common form of indirection. Instead of creating an object directly with a constructor, you obtain the object from a Factory class method. This method hides the actual implementation of the object's creation from the caller (see Example 11-7).

Example 11-7. ZipCodeVerificationServiceFactory
enum ZipCodeVerificationServiceType {NORMAL, TRACKING};
class ZipCodeVerificationServiceFactory
    {
    static ZipCodeVerificationService get_instance
        (ZipCodeVerificationServiceType type_to_instantiate);
        {
        switch(type_to_instantiate)
            {
        case NORMAL:
            return new ZipCodeVerificationImplementation( );
            break;
        case TRACKING:
            return new ZipCodeVerificationTracker( );
            break;
        }
    }

We alter the initialization of zip_code_verification in Example 11-4 to call the factory get_instance( ) method with the type requested (NORMAL or TRACKING):

    static ZipCodeVerificationService zip_code_verification =
        ZipCodeVerificationServiceFactory.get_instance(TRACKING);

Note that the caller can choose his desired implementation type, but does not need to specify the name of the actual implementation. The caller specifies the what ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required