473,770 Members | 1,757 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class object factories, references to a **class**

I am trying to create a way to register static members of a **class**, not
an object, for making an object factory. The main thing I want is to be
able to make a call like

class MyClass
{
public:
MyClass *factory();
};
register(MyClas s);

and have a method that calls MyClass::factor y() to return a MyClass object
on a call like 'MyClass *o = create("MyClass ");'.

Is there any C++ construct that would allow this sort of class registration?
I'd be into using macros and even templates (hopefully not).
Here is a longer example...

main.cpp:
------------------------------------------
#include <map>
#include <typeinfo>

typedef std::map<const char *, void (something::*)( )> FactoryMap;

FactoryMap *getMap()
{
// I need there to be exactly one instance of registry.
static FactoryMap registry;
return &registry;
}

int register(someth ing Class)
{
pair<const char *, void (something::*)( )> p(typeid(Class) .name(),
Class::factory) ;

getMap()->insert(p);
}

void *create(const char *classname)
{
FactoryMap::ite rator it = getMap()->find(classname );
if(it != getMap()->end())
return it->second();
else
return NULL;
}

class A
{
public:
static A *factory(){retu rn new A;}
};
int aDummy = register(A); // THIS IS THE SORT OF CALL I'M AFTER
class B : public A
{
public:
static A *factory(){retu rn new B;}
};
int bDummy = register(B); // AGAIN, THIS IS THE SORT OF CALL I'M AFTER

int main()
{
A *a = *b
}

Jul 22 '05 #1
1 3001

"Patrick Stinson" <aj*****@gci.ne t> wrote in message
news:10******** *****@corp.supe rnews.com...
I am trying to create a way to register static members of a **class**, not
an object, for making an object factory. The main thing I want is to be
able to make a call like

class MyClass
{
public:
MyClass *factory();
};
register(MyClas s);

and have a method that calls MyClass::factor y() to return a MyClass object
on a call like 'MyClass *o = create("MyClass ");'.

Is there any C++ construct that would allow this sort of class registration? I'd be into using macros and even templates (hopefully not).
Here is a longer example...

main.cpp:
------------------------------------------
#include <map>
#include <typeinfo>

typedef std::map<const char *, void (something::*)( )> FactoryMap;

FactoryMap *getMap()
{
// I need there to be exactly one instance of registry.
static FactoryMap registry;
return &registry;
}

int register(someth ing Class)
{
pair<const char *, void (something::*)( )> p(typeid(Class) .name(),
Class::factory) ;

getMap()->insert(p);
}

void *create(const char *classname)
{
FactoryMap::ite rator it = getMap()->find(classname );
if(it != getMap()->end())
return it->second();
else
return NULL;
}

class A
{
public:
static A *factory(){retu rn new A;}
};
int aDummy = register(A); // THIS IS THE SORT OF CALL I'M AFTER
class B : public A
{
public:
static A *factory(){retu rn new B;}
};
int bDummy = register(B); // AGAIN, THIS IS THE SORT OF CALL I'M AFTER

int main()
{
A *a = *b
}


Patrick,

here's an outline of a solution - basically I've used templates to make
factory objects out of
your classes so I can call their static methods through a virtual function.
The registration
process creates a mapping of factory to name, so you can do
factory.create( "foobar").

dave

#include <stdio.h>
#include <string>
#include <map>
using namespace std;

class MyClass
{
public:
virtual void dofoo()=0;
};

class ClassFactory
{
public:
virtual MyClass* create()=0;
virtual string name()=0;

};
template < class T >
class FactoryWrapper : public ClassFactory
{
public:
virtual MyClass* create(){ return T::create();}
virtual string name(){ return T::name();}
};

class Factories
{
public:
void registerFactory ( ClassFactory* factory)
{
_facts[factory->name()]=factory;
}
MyClass* create( const string& name)
{
if ( _facts[name] )
{
return _facts[name]->create();
}

return 0;
}
map<string, ClassFactory*> _facts;

};
class Class1 : public MyClass
{
public:
static Class1* create(){ return new Class1();};
virtual void dofoo(){ printf("Class1: :dofoo\n");};
static string name(){ return "Class1";} ;

};
class Class2 : public MyClass
{
public:
static Class2* create(){ return new Class2();};
virtual void dofoo(){ printf("Class2: :dofoo\n");};
static string name(){ return "Class2";} ;

};

int main(int argc, char* argv[])
{
FactoryWrapper< Class1> class1Factory;
FactoryWrapper< Class2> class2Factory;
Factories factories;

factories.regis terFactory(&cla ss1Factory);
factories.regis terFactory(&cla ss2Factory);

MyClass* c1= factories.creat e("Class1");
MyClass* c2= factories.creat e("Class2");
c1->dofoo();
c2->dofoo();

return 0;
}

Jul 22 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1414
by: Jeff Louie | last post by:
Well I finally finished a Chapter on the use of Type Based and Interface Based Class Factories in C# at: http://www.geocities.com/jeff_louie/OOP/oop18.htm Happy Holidays, Jeff *** Sent via Developersdex http://www.developersdex.com ***
1
2114
by: Hans-Christian Stadler | last post by:
Hi, I'm wondering how C++ .NET initializes class members. I have code that looks aproximately like this: _gc class SuperClass; // Factory object creates instances _gc class Factory { public:
8
4814
by: deko | last post by:
Which layer should a Factory class go in? DA - Data Access BL - Business Logic UI - User Interface ??
9
1863
by: sashang | last post by:
Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict, extra_information): super(MetaThing, cls).__init__(name, bases, dict)
37
4027
by: JohnGoogle | last post by:
Hi, Newbie question... After a recent article in VSJ I had a go at implementing a Fraction class to aid my understanding of operator overloading. After a previous message someone suggested that I implement it as a struct rather than a class which I did and all worked OK. The simplest declaration for the struct is:
4
2442
by: Chris Brat | last post by:
Hi, I've done some reading up but I cant get my head around how/why class methods can be used as apposed to static methods. Can anyone give an example of where they have used class methods? Thanks, Chris
25
2148
by: David Sanders | last post by:
Hi, As part of a simulation program, I have several different model classes, ModelAA, ModelBB, etc., which are all derived from the class BasicModel by inheritance. model to use, for example if the parameter model_name is "aa", then choose ModelAA. Currently I do this as follows:
1
1056
by: Smokey Grindle | last post by:
Any good examples out there of remoting with class factories out there? I want to use interfaces to keep my code server side but also need class factories to make the objects. havent figured out exactly how to do this.. thanks!
6
1662
by: K Viltersten | last post by:
I have a class that reads an XML and according to its contents, it creates a List<Letter>, where Letter is an abstract class that is implemented in Alpha and Beta classes. I use a foreach statement consisting of a switch upon which i create an instance of e.g. Alpha an add it to the list.
0
9617
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10099
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10037
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9904
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.