Design Patterns: Factory Method
Another design pattern today! The second most common (after the singleton) is, in my opinion, factory method. It's a creational design pattern that is useful when you need to control creation process of the objects a little more than by a constructor.
For instance you might want to decide what subclass to create at the runtime rather than while writing the code. Or you don't care what subclass will be constructed. Factory method in some more advanced implementations also allows reusing old objects insead of always creating new instances. The_factory metho_ will give you an object when you request it, but the creation process is encapsulated. That encapsulation is enforced, and allows an object to be requested without inextricable coupling to the act of creation.
Detailed description of the design pattern can be found at
I'll just throw in the code. In my examples, there's a base class - a
and two subclasses
BlueCup . The base class has a factory method
that will get you a cup of the color you like.
/* This is the factory method. */
static Cup* getCup(std::string color);
class RedCup : public Cup
color = "red";
class BlueCup : public Cup
color = "blue";
Cup* Cup::getCup(std::string color)
if (color == "red")
return new RedCup();
else if (color == "blue")
return new BlueCup();
/* A little testing */
/* Now we decide the type of the cup at
* runtime by the factory method argument */
Cup* redCup = Cup::getCup("red");
std::cout << redCup->color << std::endl;
Cup* blueCup = Cup::getCup("blue");
std::cout << blueCup->color << std::endl;
The whole source file is available on github.
color = ""
# This is the factory method
if (cupColor == "red"):
elif (cupColor == "blue"):
color = "red"
color = "blue"
# A little testing
redCup = Cup.getCup("red")
print "%s(%s)" % (redCup.color, redCup.__class__.__name__)
blueCup = Cup.getCup("blue")
print "%s(%s)" % (blueCup.color, blueCup.__class__.__name__)
The whole source text is available on github.