Skip to Content
Hands-On Design Patterns with C++
book

Hands-On Design Patterns with C++

by Fedor G. Pikus
January 2019
Intermediate to advanced
512 pages
14h 5m
English
Packt Publishing
Content preview from Hands-On Design Patterns with C++

The basics of the Factory method

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Structural Design Patterns in Modern C++

Structural Design Patterns in Modern C++

Umar Lone

Publisher Resources

ISBN: 9781788832564Supplemental Content