Question #2: In object-oriented programming (C++), describe how Factory methods
ID: 3866222 • Letter: Q
Question
Question #2: In object-oriented programming (C++), describe how Factory methods of a specific derived class implementation are called.
Provide an example.
Textbook for reference: Horstmann C.S., & Budd T.A.(2009). Big C++ (2nd Edition). Wiley publication. ISBN: 978-0-470-38328-5 page 946
Excerpt from page 917 to explain the GoF:
“As you can see, a pattern is more abstract than an algorithm. An algorithm gives you specific instructions how to implement a computation. A pattern gives you advice on solving a design problem. The influential book, Design Patterns by Gamma, Helm, Johnson, and Vlissides, contains a description of many patterns for software design, including the ITERATOR pattern. (See [2].) Because the book has four authors, it is sometimes referred to as the “Gang of Four” (GoF) book. (The original Gang of Four were radical Chinese communists who were advocates of the Cultural Revolution. There is no apparent connection between the two “gangs” beyond the fact that they each have four members.) In this chapter, we cover five of the patterns in the Design Patterns book: ITERATOR, ADAPTER, TEMPLATE METHOD, STRATEGY, and COMPOSITE.”
Explanation / Answer
Factory Method Pattern is used in following scenarios:
People often use Factory Method as the standard way to create objects; but it isn't necessary if: the class that's instantiated never changes, or instantiation takes place in an operation that subclasses can easily override (such as an initialization operation).
Factory Method is similar to Abstract Factory but without the emphasis on families.
Factory Methods are routinely specified by an architectural framework, and then implemented by the user of the framework.
Now comes the Factory class. This is a singleton pattern implementation--meaning only one instance of the factory can ever be instantiated, no more, no less
Factory Class Implementation
Now we need to work out a few definitions of the AnimalFactory class. Specifically the constructor, the Register, and the CreateAnimal functions.
Constructor
The constructor is where you might consider registering your Factory functions. Though this doesn’t have to be done here, I’ve done it here for the purposes of this example. You could for instance register your Factorytypes with the Factory class from somewhere else in the code.
Hide Copy Code