0% found this document useful (0 votes)
22 views

Mike Shah CPPCON 2021 Software Design Track Factory Pattern

Uploaded by

Sundar Nil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Mike Shah CPPCON 2021 Software Design Track Factory Pattern

Uploaded by

Sundar Nil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Add cover slide

1
Please do not redistribute slides without
prior permission.

2
Software Design:
Factory Pattern
Mike Shah, Ph.D.
@MichaelShah | mshah.io | www.youtube.com/c/MikeShah
2:00 pm MDT, Wed. October 27
60 minutes | Introductory Audience 3
The abstract that you read and enticed
Abstract you to join me is here!
C++ programs that are dynamic in nature have to create objects at some time during run-time. New
objects can be created by explicitly calling ‘new’ and then the data type of that object. However, this
requires that a programmer knows at ‘compile-time’ what object should be created. What we would like,
is to have a layer of abstraction, or someway to create objects at run-time to reflect the dynamic nature
of some C++ programs. Luckily, there is a common pattern that can help solve this problem--the factory
design pattern.

In this talk, we are going to discuss a creational design pattern known as a factory. The pattern can be as
simple as a function, or take on other forms as a distributed factory, or an abstract factory. We’ll show
some basic examples of a factory in modern C++ as well as real world use cases of where factories
occur for further study. Finally, we’ll discuss the tradeoffs of the factory pattern, and discuss which
scenarios you may not actually want to use a factory. Attendees will leave this talk with the knowledge to
go forward and implement the factory pattern, as well as how to spot the factory pattern in projects they
may already be working on!
4
Code for the talk
Available here: https://github.com/MikeShah/cppcon2021

5
Who Am I?
by Mike Shah

● Assistant Teaching Professor at Northeastern University in


Boston, Massachusetts.
○ I teach courses in computer systems, computer graphics,
and game engine development.
○ My research in program analysis is related to performance
building static/dynamic analysis and software visualization
tools.
● I do consulting and technical training on modern C++,
Concurrency, OpenGL, and Vulkan projects
○ (Usually graphics or games related)
● I like teaching, guitar, running, weight training, and anything in
computer science under the domain of computer graphics,
visualization, concurrency, and parallelism.
6
● Contact information and more on: www.mshah.io
Who Am I?
by Mike Shah

● Assistant Teaching Professor at Northeastern University in


Boston, Massachusetts.
○ I This
teachwill
courses
be anin computer systems,
interactive computer
session, graphics,
please shout out
and game engine development.
answers
○ My research in program analysis is related to performance
building static/dynamic analysis and software visualization
tools.

(Note: I never call on audience members randomly, I
I do consulting and technical training on modern C++,
did notOpenGL,
Concurrency, like thatandasVulkan
a student)
projects
○ (Usually graphics or games related)
● I like teaching, guitar, running, weight training, and anything in
computer science under the domain of computer graphics,
visualization, concurrency, and parallelism.
7
● Contact information and more on: www.mshah.io
I was asking a few folks at the conference earlier
a question:

8
I was asking a few folks at the conference earlier
a question:

How did you get your start in Programming?


(Or rather--what domain peaked your interest?)

9
Video Games! (That’s my answer) (1/2)

(Here are some favorites from around the time I was learning how to program, can you name them all?)
10
Video Games! (That’s my answer) (2/2)

And for this talk--I don’t care if you like games (that’s
totally fine!), or if you do not know anything about them
at all.

But I do think games are an interesting use case case


of real-time systems.

(Here are some favorites from around the time I was learning how to program, can you name them all?)
11
Real time systems (1/2)
● So just looking at the animation on
the right--there is a lot going on.
○ There are many different types of
objects
■ Some of these objects are being
destroyed
■ New objects are being created
○ Objects are moving around
○ Artificial intelligence (path finding and
other decision making)
Command and Conquer Red Alert
○ In-game resource management is
taking place

12
Real time systems (2/2)
● So just looking at the animation on


For today’s talk, I want us to
the right--there is a lot going on.
There are many different types of

think about software design for


objects
■ Some of these objects are being
destroyed
a real time application--I’ll use
■ New objects are being created
○ Objects are moving around
○ a ‘game’ as an example
Artificial intelligence (path finding and
other decision making)
Command and Conquer Red Alert
○ In-game resource management is
taking place

13
My expectations and why this talk exists (1/2)
● This talk is part of the Software Design Track at Cppcon
○ Klaus Iglberger and I (Klaus doing the majority of the work!) put together the software design
track
■ Part of this track we thought would be good to have some ‘tutorial like’ or ‘more
fundamental’ (i.e. like the back to the basics) talks on Design Patterns.
■ (Perhaps 1 or 2 talks like this a year--stay tuned and submit to future Cppcons!)
● So this probably is not an ‘expert-level’ talk, but aimed more at beginners
○ That said, I hope experts will derive some value for looking at today’s pattern.
■ Or otherwise, be able to refresh and point out some tradeoffs with today’s pattern
● The design pattern of today is....
○ But before I spoil the pattern (even though it’s the name of the talk) let’s think about what our
goals are

14
My expectations and why this talk exists (2/2)
● This talk is part of the Software Design Track at Cppcon
○ Klaus Iglberger and I (Klaus doing the majority of the work!) put together the software design
track
■ Part of this track we thought would be good to have some ‘tutorial like’ or ‘more
fundamental’ (i.e. like the back to the basics) talks on Design Patterns.
■ (Perhaps 1 or 2 talks like this a year--stay tuned and submit to future Cppcons!)
● So this probably is not an ‘expert-level’ talk, but aimed more at beginners
○ That said, I hope experts will derive some value for looking at today’s pattern.
■ Or otherwise, be able to refresh and point out some tradeoffs with today’s pattern
● The design pattern of today is....
○ But before I spoil the pattern (even though it’s the name of the talk) let’s think about what our
goals are

15
A user-driven application
(e.g., a video game)

16
Question to Audience:
● If I have a user-driven application (Observe the user creating a new
(e.g., a game) object)
● And part of that game is the users
ability to ‘create’ objects at
run-time.
○ How well do you think I as a developer
can predict at compile-time what
objects to create?
● What are your thoughts?

17
Thought Process (1/16)
● How well do you think I as a (Observe the user creating a new
developer can predict at object)
compile-time what objects to create?
(in a very dynamic program...)

18
Thought Process (2/16)
● How well do you think I as a
developer can predict at
compile-time what objects to create?
(in a very dynamic program...)
○ Maybe we could guess 100 of each type
of our objects?
○ Maybe we have played our game a few
times and ‘100’ feels like a good number
(or otherwise you have empirical
evidence).
■ What happens if a player goes
over?
■ Maybe we restrict them? Maybe
reallocate 19
In a video game, let’s assume
Thought Process (3/16)
these objects are potentially
very large

● How
We maywell doofyou
run out stackthink
spaceI as a
here! (Click here
developer can topredict
review at
stack memory)
compile-time what objects to create?
(in a very dynamic program...)
○ Maybe we could guess 100 of each type
of our objects?
○ Maybe we have played our game a few
times and ‘100’ feels like a good number
(or otherwise you have empirical
evidence).
■ What happens if a player goes
over?
■ Maybe we restrict them? Maybe
reallocate 20
Thought Process (4/16)
● How well do you think I as a
developer can predict at
compile-time what objects to create?
(in a very dynamic program...)
○ So, let’s allocate our memory on the heap.
■ We can also resize if the user goes
over the limit.
● What’s the problem here?

21
Well, if I need 200 units, that copy takes O(n) time.

Thought Process (3/16)


(Or--even if I shrink the array, I have to reallocate.)

● How well do you think I as a


developer can predict at compile-time
what objects to create? (in a very
dynamic program...)
○ So, let’s allocate our memory on the heap.
■ We can also resize if the user goes
over the limit.
● What’s the problem here?

22
Thought Process (6/16)
● How well do you think I as a
developer can predict at
compile-time what objects to create?
(in a very dynamic program...)
○ So I don’t want to manage resizing, so I’ll
just use a data structure.
■ I could also preallocate some
objects (say 100 again) if I know
that’s reasonable for the game.
● (Often games prefer to
preallocate (i.e., give you a
load screen))

23
Thought Process (7/16)
● How well do you think I as a
developer can predict at compile-time
what objects to create? (in a very
dynamic program...)
■ Now, what if half-way through
development the team decides we
don’t want ‘ObjectType3’--it does
not make the game fun?
● I have to delete everywhere.

24
Thought Process (8/16)
● How well do you think I as a
developer can predict at compile-time
what objects to create? (in a very
dynamic program...)
○ Okay, ObjectType3 is gone.
■ I still need to create my 100 objects,
and perhaps some of them are going
to be different (meaning created
using different constructors)...

25
Thought Process (9/16)
● How well do you think I as a
developer can predict at compile-time
what objects to create? (in a very
dynamic program...)
○ Wait...
○ How do I even construct my objects?
■ What if there are multiple
constructors?
■ Do I think I’ll be able to guess at
compile-time which one to use?

26
Thought Process (10/16)
● How well do you think I as a
developer can predict at compile-time
what objects to create? (in a very
dynamic program...)
○ Wait...
○ How do I even construct my objects?
■ What if there are multiple
constructors?
■ Do I think I’ll be able to guess at
compile-time which one to use?
● Okay, I can again try to fix
that...let’s just have one
function (and I need to do this
for each type) 27
Thought Process (11/16)
And●maybe
How I could
wellgeneralize this function
do you think I as ato
handle the creation of multiple objects.
developer can predict at compile-time
Certainly that could
what be a to
objects parameter!
create? (in a very
dynamic
If there are differentprogram...)
numbers of arguments....well,
I’ll just use
○ theWait...
maximum number (and guess the
types that○may be used...)
How do I even construct my objects?
■ What if there are multiple
Hmm, I probably should be careful about passing
in my std::vector asconstructors?
a parameter--but by reference
is okay... ■ Do I think I’ll be able to guess at
compile-time which one to use?
● Okay, I can again try to fix
that...let’s just have one
function (and I need to do this
for each type) 28
Thought Process (12/16)
So we’re slowly getting closer to something interesting
● How well do you think I as a
here.
developer can predict at compile-time
I like that we can create all of our objects in one place.
what objects to create? (in a very
The parameters and their types that may (or may not
dynamic program...)
be used) is concerning to get correct.
○ Wait...
I also don’t○ particularly
How do Ilike
even construct
that we made myunits1
objects?
and
units2 global to ■simplify
Whatthis function
if there are multiple
constructors?
And, I’m starting to think about where these objects will
■ Do I think I’ll be able to guess at
live (right now in a global vector...probably a bad idea)
compile-time which one to use?
● Okay, I can again try to fix
that...let’s just have one
function (and I need to do this
for each type) 29
So... this works.

Question to Audience:
● How well do you think I as a
developer can predict at compile-time
what objects to create? (in a very
dynamic program...)
Question○ toWait...
Audience: How do I know when
I’m done?
○ How do I even construct my objects?
(Your thoughts)
■ What if there are multiple
constructors?
■ Do I think I’ll be able to guess at
compile-time which one to use?
● Okay, I can again try to fix
that...let’s just have one
function (and I need to do this
for each type) 30
So... this works.

Question
Question to Audience:
to Audience: How do I know when
I’m done?
● thoughts)
(Your How well do you think I as a
developer can predict at compile-time
● Maybe
what aobjects
deadline hits, maybe
to create? (in ait’s good
very
enough,
dynamicmaybe we are tired...
program...)
● How○ about
Wait...some better criteria--where I
can○check
How off
do I three boxes my objects?
even construct
○ When ■ we’re
What if convinced our solution
there are multiple
(especially if the code is going to live
constructors?
■ Do
a long I think
time) is:I’ll be able to guess at
compile-time which one to use?
❏ Flexible
● Okay, I can again try to fix
❏ Maintainable that...let’s just have one
❏ Extensible function (and I need to do this
for each type) 31
●So is this code (‘makeObject’ specifically)
○ Flexible?
Question to Audience:
❏ (your thoughts?)
○ Maintainable
● How well do you think I as a
❏ (your thoughts?)
developer can predict at compile-time
○ Extensible
what objects to create? (in a very
❏ (your thoughts?)
dynamic program...)
○ Wait...
○ How do I even construct my objects?
■ What if there are multiple
constructors?
■ Do I think I’ll be able to guess at
compile-time which one to use?
● Okay, I can again try to fix
that...let’s just have one
function (and I need to do this
for each type) 32
● So is this code (‘makeObject’ specifically)
○ Flexible?
Question to Audience:
❏ sort-of, we can extend our list of objectTypes
❏ But how many params should we add?
❏ Maybe we can have a separate
● How well doObjParamsType
you think Iand as use
a inheritance
developer can for the types (okay
predict interesting
at compile-time
idea...needs to be worked out more)
○ Maintainable? to create? (in a very
what objects
dynamic
❏ Notprogram...)
really
○ Wait... ❏ If I remove an object type, do I
○ How do Irenumber?
even construct my objects?
❏ What
■ What if thereaboutarethemultiple
parameters?
❏ How much knowledge do I need to
constructors?
add to this function--it seems like a lot!
■ Do I think I’ll be able to guess at
○ Extensible?
compile-time which one to use?
❏ I suppose--we can add ObjectTypes
❏ BUT,●we have Okay,toI figure
can again try tovector
out which fix to
add to... that...let’s just have one
● I’ll give this score a 1function (and Ican
out of 3--we need to do this
probably do
better. for each type) 33
What Problem Am I Trying to Solve?
Claim: If I have a user-driven application (e.g., a game)

A. It can be difficult to figure out how to create objects of different types


a. (And we probably cannot do this well at compile-time)
B. It can be difficult to figure out ‘where’ to create objects
a. (i.e., If I have lots of free functions)

And it’s worth thinking about this problem at scale--where I have 10 different
types, or even 100 different object types.

34
So let’s think about this game (1/2)
● There are many different types of objects
○ How do we create the different objects in this
real-time application such that our code design
is:
■ flexible
■ maintainable
■ and extensible
○ In other words--what is the right pattern?

35
Command and Conquer Red Alert
So let’s think about this game (2/2)
● There are many different types of objects
○ How do we create the different objects in this
real-time application such that our code design
is:
Luckily, some smart folks have thought
■ flexible about this problem.
■ maintainable
■ and extensible

We have a design pattern to help us
In other words--what is the right pattern?
create objects

36
Command and Conquer Red Alert
Design Patterns
‘templates’ or ‘flexible blueprints’ for developing software.

37
What is a Design Pattern?
● A common repeatable solution for solving problems.
○ Thus, Design Patterns can serve as ‘templates’ or ‘flexible blueprints’ for developing
software.
● Design patterns can help make programs more:
○ Flexible
○ Maintainable
○ Extensible
○ (Recall, these are our three criteria we’d like to satisfy)

38
Design Patterns Book
● In 1994 a book came out collecting heavily used
patterns in industry titled “Design Patterns”
○ It had four authors, and is dubbed the “Gang of Four” book
(GoF).
○ The book is popular enough to have it’s own wikipedia
page: https://en.wikipedia.org/wiki/Design_Patterns
○ C++ code samples included, but can be applied in many
languages.
○ This book is a good starting point on design patterns for
object-oriented programming

* See also the 1977 book “A Pattern Language: Towns, Buildings, Construction” by Christopher Alexander et al. where I believe the term design
39
pattern was coined.
Design Patterns Book * Brief Aside *
● In 1994 a book came out collecting heavily used
patterns in industry titled “Design Patterns”
○ It had four authors, and is dubbed the “Gang of Four” book
● I really enjoyed this book (as a graphics
(GoF).

programmer) for learning design patterns.
It is popular enough to have a wikipedia page:
○ There’s a free web version here:
https://en.wikipedia.org/wiki/Design_Patterns
○ C++ code samples included, buthttps://gameprogrammingpatterns.com/
can be applied in many
languages. ○ I also bought a physical copy to keep
○ on my
This is a good starting point on design desk for
patterns
object-oriented programming

40
Design Patterns
Book (1/2)
● So design patterns are
reusable templates that can
help us solve problems that
occur in software
○ One (of the many) nice thing the
Design Patterns Gang of Four
(GoF) book does is organize the
23* presented design patterns into
three categories:
■ Creational
■ Structural
■ Behavioral

41
*Keep in mind there are more than 23 design patterns in the world
Design Patterns
Book (2/2)
● Today we are
So design focusing
patterns are on
‘creation’
reusable of objects
templates that can
help us solve problems that
I’ve in
occur highlighted
software the 5
○ creational patterns.
One (of the many) nice thing the
Design Patterns Gang of Four
(GoF) book does is organize the
23* presented design patterns into
three categories:
■ Creational
■ Structural
■ Behavioral

42
*Keep in mind there are more than 23 design patterns in the world
Creational Design
Patterns

43
Creational Design Patterns
● Provide program more flexibility on how to create objects,
often avoiding direct instantiation of a specific object.
○ So this means:
■ We try to avoid directly creating instances of objects in our code:
● ObjectType1 myObject = new ObjectType1;
■ We prefer instead to encapsulate how an object is created

44
https://en.wikipedia.org/wiki/Design_Patterns#Patterns_by_type
We are close to a creational pattern here

● We are somewhat encapsulating


how we create our objects
○ It’s just not very robust
■ What if a user types in an ‘int’ for
the wrong objectType
■ Or we otherwise remove
objectType’s
● (We also need to remove our
vector)
○ We need to clean this up--and it will
require thinking about our ‘ObjectType’
with a little more structure.

45
Quick Refresh: Object-Oriented Programming Toolbox
● One of our tools that we can utilize is
inheritance
○ This is a mechanism where we create an is-a
relationship between two types
■ The relationship is a parent-child
relationship
■ (e.g., on right, we see that a ‘Dog’ is-an
‘Animal’
● Now, I can use the ‘is-a’ relationship to
my advantage and utilize polymorphism
○ (i.e., inheritance based polymorphism)

https://cdn.programiz.com/sites/tutorial2program/files/cpp-inheritance.png 46
We were close in solving our problem

47
Our Object Inheritance Hierarchy (1/4)
● So to start, we’re going to want
some common Interface for which
our different game objects can
inherit from
○ This is probably a good idea to enforce
(with the pure virtual member functions)
properties of each Game Object.
○ Second, we can inherit from any
IGameObject from this common
interface to help ease our construction
of different types of objects.
■ (again leveraging
inheritance-based polymorphism)
48
Our Object Inheritance Hierarchy (2/4)
● So to start, we’re going to want
some common Interface for which
our different game objects can
inherit from
○ This is probably a good idea to enforce
(with the pure virtual member functions)
properties
So observe of each Game
to the bottom-right ourObject.
inheritance
○ Second,
hierarchy we wantwetocan inherit from any
establish.
GameObject from this common
ObjectType1 IGameObject
interfaceis-a
to helpIGameObject
ease our construction
ObjectType2 is-a IGameObject
of objects.

ObjectType1 ... ObjectTypeNth


49
Our Object Inheritance Hierarchy (3/4)
● So to start, we’re going to want
some common Interface for which
our different game objects can
inherit from
○ This is probably a good idea to enforce
(with the pure virtual member functions)
properties of each Game Object.
○ Second, we can inherit from any
GameObject from this common
(Code) interface
So we’ll have something IGameObject
to help ease ourlike this for each
construction
differentofObjectType
objects. that we create

ObjectType1 ... ObjectTypeNth


50
Our Object Inheritance Hierarchy (4/4)
● So to start, we’re going to want
some common Interface for which
our different game objects can
inherit from
○ This is probably a good idea to enforce
(with the pure virtual member functions)
properties of each Game Object.
○ Second, we can inherit from any
GameObject from this common
IGameObject
interface
Two subtle to help
changes, let’sease
giveour construction
more specific
of our
names to objects (Plane and Boat), and
objects.
make sure we’re inheriting publicly
IGameObject. Plane Boat
...
51
Updated ‘function’ to create objects (1/4)
● So next I have updated our ‘creation’ function shown on the right

Before After 52
Updated ‘function’ to create objects (2/4)
● ● So next
The first Imajor
havechange
updated
is thatour
I have an enum class
‘creation’ function shown
for the ontypes
different the of
right
objects
○ (I could have also done this on the left)
○ This ensures we’ll create the correct object type (i.e., better than using a plain ‘int’)

Before After 53
Updated
● The second‘function’
major idea, is thatto create
I have objects
simplified the (3/4)
function function
○ We just return an *IGameObject
○ This is much cleaner that what we were doing previously
● So next I have updated our ‘creation’ function shown on the right
■ (The managing of which collection to push to is gone!)
○ We’re also moving towards the ‘Single Responsibility Principle’ where I could create all
of my objects in CreateObjectFactory

Before After 54
Updated ‘function’ to create objects (4/4)
● ●SoAnother
next Ismall
havechange, is to slightly modify our return type to keep with the modern times :)
updated our ‘creation’ function shown on the right
○ I recommend shared_ptr for this game example.
○ In a game, we might have multiple pointers to the same resource
■ e.g. Objects may share resources (e.g., pixel data, texture, etc.)

Before After 55
Usage in Main Loop (1/3)
● Here’s the creation of our
two different object types
(Boat’s and Planes)
○ Notice we only now have 1
collection (std::vector) to
store our types
■ (Due to our
abstraction layer for
IGameObject)

56
Usage in Main Loop (2/3)
● Here’s the creation of our
two different object types
(Boat’s and Planes)
○ Notice we only now have 1
collection (std::vector) to
store our types
■ (Due to our
abstraction layer for
IGameObject)
○ Additionally notice the
‘main game loop’ is
simplified
■ We only have to
iterate through one 57
collection
Usage in Main Loop (3/3)
● Here’s the creation of our
two different object types
(Boat’s and Planes)
○ Notice we only now have 1
collection (std::vector) to
store our types
■ (Due to our
abstraction layer for
IGameObject)
○ Additionally notice the
‘main game loop’ is
simplified Note: To experts--we can refactor for performance and a more
■ We only have to ‘data-oriented’ approach. That is a separate talk--this is fine
iterate through one for our needs for now.
58
collection
We have implemented
The Factory Method
(A creational design pattern)

59
The Factory Method (1/5)
The Factory Method pattern provides a
generalized way to create instances of
an object and can be a great way to
hide implementation details for derived
class
Here is our factory--and perhaps we should also add a ‘default’ case
which returns nullptr.

60
The Factory Method (2/5)
The Factory Method pattern provides a
generalized way to create instances of
an object and can be a great way to
hide implementation details for derived
class
Here is our factory--and perhaps we should also add a ‘default’ case
● Yes, we have that! which returns nullptr.
○ We can add new types to our enum
class and function easily.

61
The Factory Method (3/5)
The Factory Method pattern provides a
generalized way to create instances of
an object and can be a great way to
hide implementation details for derived
class
Here is our factory--and perhaps we should also add a ‘default’ case
● We could extend our enum class which returns nullptr.
creatively as well
■ e.g., PLANE_IN_AIR
● This handles constructing the
same types with different
parameters or setup functions
62
The Factory Method (4/5)
The Factory Method pattern provides a
generalized way to create instances of
an object and can be a great way to
hide implementation details for derived
class
Updated with another object type (PLANE_IN_AIR) that we can create

63
The Factory Method (5/5)
The Factory Method pattern provides a
generalized way to create instances of
an object and can be a great way to
hide implementation details for
derived class

● This we did not talk about, but we


can hide our implementation to
clients of our API fairly well
This is the Factory.hpp
○ Client really only needs to know that Here I’m only exposing the enum class (which could also be hidden) to
they can create IGameObject’s the client of our API.

(Full example in ./simplefactory -- Not 100% optimal, but shows how to


setup your Factory in a header file) 64
The Factory Method - Pros and Cons? (1/2)
● So, no design pattern is perfect,
computer science is about
trade-offs.
○ What do we like about this?
■ (i.e., the pros)
○ (Question to the audience)
■ Is this pattern: Here is our factory--and perhaps we should also add a ‘default’ case
● Flexible which returns nullptr.

● Maintainable
● Extensible
○ What do we dislike?
■ (i.e., the cons)

65
The Factory Method - Pros and Cons? (2/2)
● Pros
○ Flexible
■ Relatively flexible
○ Maintainable
■ 1 update to the enum class, and one update to
the switch statement--not too bad.
○ Extensible
■ Creating new object types is done through
inheritance is easy
● Cons
Here is our factory--and perhaps we should also add a ‘default’ case
○ May need several factories for different hierarchies
which returns nullptr.
○ Still potentially two ‘updates’ in two places of our code
(i.e. the enum class and then in our actual function)
■ So potentially over-engineered for a very small
project
● Other thoughts
○ You should probably think more about if you want to use
shared_ptr or unique_ptr for your domain
■ (i.e., think about your ownership)
○ Probably need a way to ‘destroy’ all objects. 66
Some other *neat* ideas - Example of loading objects
● We can make our application
data-driven using some
simple configuration file
○ Much more intuitive in
our pattern

level1.txt 67
Some other *neat* ideas - Tracking Object Counts
● We may also want to manage
object counts.
○ Several ways to do so
■ Could do it directly in each of our
game objects
● Remember one of our earlier
questions:
○ How well do you think I as a developer
can predict at compile-time what
objects to create? (slide 17)
○ (The answer might be--an exact
number)

68
Let’s make our factory more extendable
Extensible Factory (Alexandrescu, 2001 in Modern C++ Design)
(Example based on Martin Reddy’s API Design for C++)

69
The Goal is to allow us at run-time to create new types (1/4)

● And this makes sense for a


game, or some system that
may be long running (and we
want flexibility)
○ So I am going to create a
‘MyGameObjectFactory’
○ My class has all static member
functions for now...I want to
keep things simple
■ Pros/Cons of that can be
discussed.

70
The Goal is to allow us at run-time to create new types (2/4)

● And thiskey
So the makes sense is
component forthe
a
game,
ability or some system
to ‘register’ and that
‘unregister’
may be longobject
runningtypes.
(and we
want flexibility)
Our types will now be stored
○ So I am going to create a
in a ‘MyGameObjectFactory’
std::map
○ My class has all static member
functions for now...I want to
keep things simple
■ Pros/Cons of that can be
discussed.

71
The Goal is to allow us at run-time to create new types (3/4)

● And thiswhatever
So for makes sense
type weforare
a
game, or some
creating, system
we’ll pass in a that
callback
may function
be long for that
running (andtype.
we
want flexibility)
This is one way you could
○ So I am going to create a
implement a ‘plugin system’
‘MyGameObjectFactory’
to your software.
○ My class has all static member
functions for now...I want to
keep things simple
■ Pros/Cons of that can be
discussed.

72
The Goal is to allow us at run-time to create new types (4/4)

● And
Our this makes
previous sensePattern’
‘Factory for a
game, or some
is almost system that
the same.
may be long running (and we
The difference
want flexibility) is we have to
search for the type (as new
○ So I am going to create a
types could be registered at
‘MyGameObjectFactory’
run-time at any time)
○ My class has all static member
functions for now...I want to
(Maybe this is not as fast or direct--as always,
keep
patterns havethings simple
trade-offs)
■ Pros/Cons of that can be
discussed.

73
Creating our Previous Types (1/2)
● To the right we can see
how to create our
previous types: plane
and boat.

74
Creating our Previous Types (2/2)
● To the right we can see
how to create our
previous types: plane
and boat.

And here is our new data type (created by a user),


and then later registered by the user
75
Is this pattern actually used?

76
Factory Method/Pattern Usage (1/6)
● I dug around a few open source projects to see if the factory pattern is
actually used
○ grep -irn “factory” .
● The answer is yes!

77
Factory Method/Pattern Usage
● I dug around a few open source projects to see if the factory pattern is
actually used
○ grep -irn “factory” .
● The answer is yes!
● https://github.com/horde3d/Horde3D

78
Factory Method/Pattern Usage
● I dug around a few open source projects to see if the factory pattern is
actually used
○ grep -irn “factory” .
● The answer is yes!
● https://github.com/OGRECave/ogre

79
Factory Method/Pattern Usage
● I dug around a few open source projects to see if the factory pattern is
actually used
○ grep -irn “factory” .
● The answer is yes!
● https://github.com/blender/blender


80
Factory Method/Pattern Usage (5/6)
● I dug around a few open source projects to see if the factory pattern is
actually used
○ grep -irn “factory” .
● The answer is yes!
● https://github.com/id-Software/Quake-III-Arena

81
Factory Method/Pattern Usage (6/6)
● And of course--command and conquer
● https://github.com/electronicarts/CnC_Re
mastered_Collection
○ (Aside, that there is a type called a ‘Factory, that is literally a ‘factory’ in the
game -- not to be confused with the pattern!)

82
Unit and Structure Hierarchy
Actual Hierarchy of Objects
● (An aside for those that are interested)
○ I also thought Jason Turners Review of the
source was interesting!
■ https://www.youtube.com/watch?v=Oe
e7gje-XRc

83
No Design Pattern is perfect -- recap
● Trade offs
○ Pros
■ Can hide lots of implementation details (only need to know type)
■ Can be extensible
○ Cons
■ Still need to document how to create the different types and what is available.
● (Maybe this is in text documentation, or maybe the factory can print a listing for
you)
■ Perhaps some performance issue if we have lots of inheritance
● (Needs to be measured, potentially able to be optimized away--I have no
empirical evidence for this specific talk)

84
‘Mike careful calling it Factory Pattern’
Factory Method Pattern (What we have largely discussed) is different and exist
several various for Factory Pattern

e.g., abstract factory, extensible factory, distributed factories, etc.


(I’m providing some key words here for you to continue forward)

85
Conclusion
A Summary of what we have learned

86
Summary of what we have learned and should learn next
● We have learned about the ‘Factory Method Pattern’
○ We have thought a bit about some of the pros and cons.
● We have learned about an extensible Factory Pattern
● We did not talk about creating multiple factories
○ (We could have used one single Templated Factory for this)
● There are several alternations of the factory pattern as well
○ The Abstract Factory Pattern is likely the most popular (and in the Gang of Four book)
■ Multiple interfaces for each of the products that you want to build.

87
Going Further
Some things that may be useful for learning more design patterns

88
Some References
● Videos
○ C++ Design Patterns: From C++03 to C++17 - Fedor Pikus - CppCon 2019
■ Overview of evolution of design patterns
○ Introduction to Design Patterns (Back to Basics Track CPPCON 2020)
■ (I give an overview and 3 patterns)
● (Some folks aren’t going to like Singleton!)
○ And many more!
■ https://www.youtube.com/results?search_query=cppcon+design+patterns
● Books
○ API Design for C++
○ Game Programming Patterns
○ Modern C++ Design

89
Code for the talk
Available here: https://github.com/MikeShah/cppcon2021

90
Software Design:
Factory Pattern
Mike Shah, Ph.D.
@MichaelShah | mshah.io | www.youtube.com/c/MikeShah

Thank you Cppcon attendees, reviewers, chairs! 91


Thank you!

92
93

You might also like