|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionHere I am introducing an easily-applicable implementation of design pattern Factory Method. BackgroundQuite often we need to create objects dynamically. At design time, we don't know what exact derived class would be needed. We need to somehow create a derived class as specified (usually according to a string called "class id") at run time, and return its pointer with its base class type. We communicate with these classes only through their common interface, which is usually an abstract class. If you are not very familiar with the term "Factory Method", a good reference can be found in the famous book Design Patterns. Or you can read the wiki page. Before I posted this article, I searched in code project and found Robert A. T. Káldy's solution Generic Class Factory, in which he also gives wonderful discussion. The method I am introducing here differs from Robert's in that mine is easier to apply. No change in the user class or project setting is needed. As to be discussed in next section, what user needs to do before calling the creator is simply to add some files into his project, and notify the factory of all the classes to be created. Using the code
Points of InterestThe method introduced here can be easily extended with other dynamic creation logic. For example, instead of creating the class according to a string id, we can enable the factory to create the class directly from an istream, like this: //current way to serialize
std::string classId;
//inStream is a given std::istream
inStream>>classId;
boost::shared_ptr<baseClass> pBase=Factory<baseClass>::Instance().createInstance(classId);
pBase->Initialize(inStream); //Initialized is a member method of baseClass
//extended way to serialize, above 3 step is done by factory
boost::shared_ptr<baseClass> pBase=Factory<baseClass>::Instance().createInstance(inStream);
HistoryI'm working for a finance company. My job often deal with a lot of peer classes, such as different assets that generate cash flows in different rules, or different tranches allocating the cash flow to different investors in different situation. At beginning a new derived class was created though a series of if-else-if comparison. it is very error-prone, especially when a new derived class were introduced. Later a factory was created for each different base class and the creator functors are stored in a map variable. Further extracting the different factories into one generic factory resulted in the method introduced here.
|
||||||||||||||||||||||