January 2019
Intermediate to advanced
512 pages
14h 5m
English
In its simplest form, the factory method constructs an object of a type that's specified at runtime:
class Base { ... };class Derived : public Base { ... };Base* p = ClassFactory( some_type_identifier, ... arguments );
How do we identify at runtime which object to create? We need some runtime identifier for each type that the factory can create. In the simplest case, the list of these types is known at compile time. Consider a game design where the player selects the type of building to construct from a menu. The program has the list of buildings that can be constructed, each represented by an object, with an identifier for each one:
enum Buildings { FARM, FORGE, MILL, GUARDHOUSE, KEEP, CASTLE};class Building ...