Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
ExampleFactory.cpp

Example for class factory

Author
woelk
Date
02/2006
/*
This file is part of the BIAS library (Basic ImageAlgorithmS).
Copyright (C) 2003-2009 (see file CONTACT for details)
Multimediale Systeme der Informationsverarbeitung
Institut fuer Informatik
Christian-Albrechts-Universitaet Kiel
BIAS is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
BIAS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with BIAS; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
@example ExampleFactory.cpp
@relates BaseFactory
@brief Example for class factory
@ingroup g_examples
@author woelk
@date 02/2006
*/
#include <Base/Common/BaseFactory.hh>
#include <string>
#include <iostream>
using namespace BIAS;
using namespace std;
/** \cond POORLY_NAMED_EXAMPLE_CLASSES
* \internal */
class Base
{
public:
Base(const string& name)
: Name_(name) {}
inline std::string GetTag() const { return Name_; }
void Who() { cout << "I am "<<Name_<<endl; }
std::string Name_;
};
/** \author woelk 02/2006
* \internal */
class A : public Base
{
public:
A() : Base("a") {};
static Base *Allocator() { return dynamic_cast<Base *>(new A); }
};
/** \author woelk 02/2006
* \internal */
class B : public Base
{
public:
B() : Base("b") {};
static Base *Allocator() { return dynamic_cast<Base *>(new B); }
};
/** \author woelk 02/2006
* \internal */
class C : public Base
{
public:
C() : Base("c") {};
static Base *Allocator() { return dynamic_cast<Base *>(new C); }
};
/** \endcond */
/* @brief explains the usage of the Factory class
@author woelk 02/2006 */
int main()
{
// main knows nothing of A, B and C
// all knowledge is in factory and henec D coudl be introduced without
// changing main
#ifdef BIAS_BUILD_SHARED_LIBS
fac->Add2Directories(".");
#else
fac->AddType((&A::Allocator));
fac->AddType((&B::Allocator));
fac->AddType((&C::Allocator));
#endif
Base *p = fac->Generate("a");
if (!p) return -1;
p->Who();
delete p; p=NULL;
p = fac->Generate("b");
if (!p) return -1;
p->Who();
delete p; p=NULL;
p = fac->Generate("c");
if (!p) return -1;
p->Who();
delete p; p=NULL;
// factory does know nothing of class with tag "d"
p = fac->Generate("d");
if (p!=NULL){
p->Who();
return -1;
} else {
cerr << "could not generate class with name \"d\""<<endl;
}
return 0;
}