Hi All,

Usually in factory method we need to check the existance of object based on given argument and then
need to return the object and due to this we need to have multiple if and else statement and while adding one more type then again one more else block with comparision block need to be added there. can anybody let me know how to achieve same without adding if-, else block or switch statement and even i needn't to compile the code.

Circle* Circle::create_instance(string name)
{
if(name == "BlueCircle")
{
return new BlueCircle;
}
else if(name == "GreenCircle")
{
return new GreenCircle;
}
// Here in this blcok without adding anything , i should be able to support new object i.e.RedCircle and there shouldn't be any compilation effort for the same.


return NULL;

}

You're asking about a templated factory in C++. They start simple and go from there. Here's something to read:

http://blog.fourthwoods.com/2011/06/04/factory-design-pattern-in-c/

If the only way you know what kind of object you want to create, though, is by reading a string, there's going to be no way around having to read that string and match it up against the right kind of object. You could make it simpler by having types register with a look-up table or some such, but it will still have to be done.

Thanks.I was looking the same.

Fastest way is for the factory to create maps of class names and ids to constructors for each. If you know the id (an integer of some sort - either 32 or 64 bit), then you don't have to interpret the string.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.