Documente Academic
Documente Profesional
Documente Cultură
Object Factory PDF
Object Factory PDF
Sabloane de proiectare
Fabrica de obiecte
Cuprins
sabloane de proiectare (software design patterns)
• fabrica de obiecte (Abstract Object Factory)
Figura ContainerFig
citeste() 1 * incarca()
Segment Cerc
citeste() citeste()
class CFigure
{
public:
virtual void print() const = 0;
virtual void save( ofstream& outFile )
const = 0;
virtual void load( ifstream& inFile ) = 0;
};
class CAbstractFigFactory
{
public:
typedef CFigure* ( *CreateFigureCallback )();
bool RegisterFigure( int figureId,
CreateFigureCallback CreateFn );
bool UnregisterFigure( int figureId );
CFigure* CreateFigure( int figureId );
private:
typedef map<int, CreateFigureCallback>
CallbackMap;
CallbackMap callbacks_;
};
bool
CAbstractFigFactory::RegisterFigure
( int figureId,
CreateFigureCallback CreateFn )
{
return
callbacks_.insert( CallbackMap::value_type
( figureId, CreateFn )
).second;
}
bool
CAbstractFigFactory::UnregisterFigure
( int figureId )
{
return
callbacks_.erase( figureId ) == 1;
}
CFigure*
CAbstractFigFactory::CreateFigure
( int figureId )
{
CallbackMap::const_iterator
i = callbacks_.find( figureId );
if ( i == callbacks_.end() )
throw string( "Unknown figure ID" );
return (i->second)();
}
private:
vector<CFigure*> figures;
// vector of pointers to figures
};
pNewFigure = CFigFactory::getInstance()->
CreateFigure( figureType );
pNewFigure->load( inFile );
add( pNewFigure );
}
}