Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ Timesaving Techniques (2005) [eng].pdf
Скачиваний:
65
Добавлен:
16.08.2013
Размер:
8.35 Mб
Скачать

Creating a Factory Class 163

Creating a Factory Class

The first step toward managing and processing objects is to create a factory class that works with a generic base class. The following steps show you how to create such a class that utilizes virtual methods to create, add, and delete objects. In this case, we create a base class called Object from which all of our managed objects will be derived.

1. In the code editor of your choice, create a new file to hold the code for the implementation of the factory code.

In this example, the file is named ch28.cpp, although you can use whatever you choose.

2. Type the code from Listing 28-1 into your file.

Better yet, copy the source file from this book’s companion Web site and change the names of the constants and variables as you choose.

LISTING 28-1: THE BASE-CLASS SOURCE CODE

#include <stdio.h> #include <string> #include <vector>

class Object

{

private:

std::string _name; bool _inUse;

public:

Object(void)

{

_name = “Object”; _inUse = false;

}

Object( const char *name )

{

_name = name; _inUse = false;

}

Object( const Object& aCopy )

{

_name = aCopy._name; _inUse = aCopy._inUse;

}

virtual ~Object()

{

}

virtual void MarkInUse( bool bFlag )

{

_inUse = bFlag;

}

virtual bool InUse( void )

{

return _inUse;

}

(continued)

164 Technique 28: Overriding Functionality with Virtual Methods

LISTING 28-1 (continued)

virtual const char *Name(void)

{

return _name.c_str();

}

virtual void Report() = 0;

};

class MyObject1 : public Object

{

public:

MyObject1()

: Object (“MyObject1”)

{

}

virtual void Report()

{

printf(“I am a MyObject1 Object\n”);

}

};

class MyObject2 : public Object

{

public:

MyObject2()

: Object (“MyObject2”)

{

}

virtual void Report()

{

printf(“I am a MyObject2 Object\n”);

}

};

class MyObject3 : public Object

{

public:

MyObject3()

: Object (“MyObject3”)

{

}

virtual void Report()

{

printf(“I am a MyObject3 Object\n”);

}

};

class Factory

{

private:

std::vector< Object *> _objects;

Creating a Factory Class 165

public:

Factory()

{

}

// Method to add an object to the pool virtual void Add( Object *obj )

{

obj->MarkInUse( true ); _objects.insert( _objects.end(), obj );

}

// Method to retrieve an object not in use virtual Object *Get( void )

{

std::vector< Object *>::iterator iter;

for ( iter = _objects.begin(); iter != _objects.end(); ++iter )

{

if ( (*iter)->InUse() == false )

{

printf(“Found one\n”);

// Mark it in use (*iter)->MarkInUse( true ); // And give it back

return (*iter);

}

}

// Didn’t find one. return NULL;

}

virtual void Remove( Object *obj )

{

std::vector< Object *>::iterator iter;

for

( iter = _objects.begin(); iter != _objects.end(); ++iter )

 

 

{

if ( (*iter) == obj )

 

 

 

 

 

 

{

 

 

 

(*iter)->MarkInUse( false );

 

 

 

break;

 

 

}

}

 

 

 

 

 

}

 

 

 

virtual

void Report()

 

1

{

 

 

std::vector< Object *>::iterator iter;

(continued)

166 Technique 28: Overriding Functionality with Virtual Methods

LISTING 28-1 (continued)

for ( iter = _objects.begin(); iter != _objects.end(); ++iter )

{

if ( (*iter)->InUse() == true )

{

printf(“Object at %lx in use\n”, (*iter) );

}

else

{

printf(“Object at %lx NOT in use\n”, (*iter) );

}

(*iter)->Report();

}

}

};

3. Save the file to disk and close the code editor.

4. Compile the application on the operating system of your choice, using your chosen compiler.

Always implement a method that can report on the state of an object of each class. This allows you to do quick memory dumps at any time, via the factory for each base class. This class can be used by a factory class to report status, and can be overridden via virtual methods to extend that status reporting for derived classes.

Testing the Factory

After you create a class, you should create a test driver that not only ensures that your code is correct, but also shows people how to use your code. The following steps show you how to create a simple test driver to illustrate how the factory class interacts with the derived objects via virtual methods.

1. In the code editor of your choice, open the source file to hold the code for the test driver.

In this example, the file is named ch28.cpp, although you can use whatever you choose.

2. Type the code from Listing 28-2 into your file.

Better yet, copy the code from the source file on this book’s companion Web site and change the names of the constants and variables as you choose.

LISTING 28-2: THE TEST DRIVER FOR THE FACTORY OBJECT

int main()

{

//Implement an object factory object Factory f;

//Add some objects to the factory MyObject1 *obj1 = new MyObject1; MyObject2 *obj2 = new MyObject2; MyObject3 *obj3 = new MyObject3;

f.Add( obj1 ); f.Add( obj2 ); f.Add( obj3 );

//Remove one to simulate the destruction of an object

f.Remove( obj1 );

//Now try to get a new one back. Object *pObject = f.Get(); printf(“I got back a %s object\n”,

pObject->Name() );