Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design 1st Edition Dmitri Nesteruk 2024 scribd download
Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design 1st Edition Dmitri Nesteruk 2024 scribd download
com
https://textbookfull.com/product/design-patterns-in-modern-
c-reusable-approaches-for-object-oriented-software-
design-1st-edition-dmitri-nesteruk/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/mastering-php-design-patterns-
develop-robust-and-reusable-code-using-a-multitude-of-design-patterns-
for-php-7-ali/
textboxfull.com
https://textbookfull.com/product/primary-mathematics-
textbook-2b-jennifer-hoerst/
textboxfull.com
Systems Analysis and Design An Object Oriented Approach
with UML Dennis
https://textbookfull.com/product/systems-analysis-and-design-an-
object-oriented-approach-with-uml-dennis/
textboxfull.com
https://textbookfull.com/product/programming-in-c-object-oriented-
features-1st-edition-laxmisha-rai/
textboxfull.com
https://textbookfull.com/product/practical-object-oriented-design-an-
agile-primer-using-ruby-second-edition-metz/
textboxfull.com
https://textbookfull.com/product/making-embedded-systems-design-
patterns-for-great-software-2nd-edition-elecia-white/
textboxfull.com
https://textbookfull.com/product/making-embedded-systems-design-
patterns-for-great-software-2nd-edition-elecia-white-2/
textboxfull.com
Design Patterns
in Modern C++
Reusable Approaches for
Object-Oriented Software Design
—
Dmitri Nesteruk
Design Patterns in
Modern C++
Reusable Approaches for
Object-Oriented Software
Design
Dmitri Nesteruk
Design Patterns in Modern C++: Reusable Approaches for Object-Oriented
Software Design
Dmitri Nesteruk
St. Petersburg, Russia
Chapter 1: Introduction������������������������������������������������������������������������1
Preliminaries���������������������������������������������������������������������������������������������������������2
Who This Book Is For���������������������������������������������������������������������������������������2
On Code Examples�������������������������������������������������������������������������������������������3
On Developer Tools������������������������������������������������������������������������������������������4
Piracy���������������������������������������������������������������������������������������������������������������5
Important Concepts�����������������������������������������������������������������������������������������������5
Curiously Recurring Template Pattern�������������������������������������������������������������5
Mixin Inheritance���������������������������������������������������������������������������������������������6
Properties��������������������������������������������������������������������������������������������������������7
The SOLID Design Principles���������������������������������������������������������������������������������8
Single Responsibility Principle������������������������������������������������������������������������8
Open-Closed Principle�����������������������������������������������������������������������������������11
Liskov Substitution Principle�������������������������������������������������������������������������18
Interface Segregation Principle���������������������������������������������������������������������21
Dependency Inversion Principle��������������������������������������������������������������������24
Time for Patterns!������������������������������������������������������������������������������������������28
iii
Table of Contents
Chapter 3: Factories���������������������������������������������������������������������������49
Scenario��������������������������������������������������������������������������������������������������������������49
Factory Method���������������������������������������������������������������������������������������������������51
Factory����������������������������������������������������������������������������������������������������������������52
Inner Factory�������������������������������������������������������������������������������������������������������54
Abstract Factory��������������������������������������������������������������������������������������������������56
Functional Factory����������������������������������������������������������������������������������������������59
Summary������������������������������������������������������������������������������������������������������������60
Chapter 4: Prototype���������������������������������������������������������������������������63
Object Constrution����������������������������������������������������������������������������������������������63
Ordinary Duplication�������������������������������������������������������������������������������������������64
Duplication via Copy Construction����������������������������������������������������������������������65
Serialization��������������������������������������������������������������������������������������������������������68
Prototype Factory������������������������������������������������������������������������������������������������72
Summary������������������������������������������������������������������������������������������������������������74
iv
Table of Contents
Chapter 5: Singleton���������������������������������������������������������������������������75
Singleton as Global Object����������������������������������������������������������������������������������75
Classic Implementation���������������������������������������������������������������������������������������77
Thread Safety������������������������������������������������������������������������������������������������79
The Trouble with Singleton���������������������������������������������������������������������������������80
Singletons and Inversion of Control��������������������������������������������������������������������84
Monostate�����������������������������������������������������������������������������������������������������������85
Summary������������������������������������������������������������������������������������������������������������86
Chapter 7: Bridge��������������������������������������������������������������������������������99
The Pimpl Idiom��������������������������������������������������������������������������������������������������99
Bridge���������������������������������������������������������������������������������������������������������������102
Summary����������������������������������������������������������������������������������������������������������105
Chapter 8: Composite�����������������������������������������������������������������������107
Array Backed Properties�����������������������������������������������������������������������������������108
Grouping Graphic Objects���������������������������������������������������������������������������������111
Neural Networks�����������������������������������������������������������������������������������������������114
Summary����������������������������������������������������������������������������������������������������������118
v
Table of Contents
Chapter 9: Decorator������������������������������������������������������������������������119
Scenario������������������������������������������������������������������������������������������������������������119
Dynamic Decorator�������������������������������������������������������������������������������������������121
Static Decorator������������������������������������������������������������������������������������������������124
Functional Decorator�����������������������������������������������������������������������������������������127
Summary����������������������������������������������������������������������������������������������������������131
vi
Table of Contents
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
Index�������������������������������������������������������������������������������������������������309
x
About the Author
Dmitri Nesteruk is a quantitative analyst,
developer, course and book author, and an
occasional conference speaker. His professional
interests lie in software development and
integration practices in the areas of computation,
quantitative finance, and algorithmic trading.
His technological interests include C# and
C++ programming as well high-performance
computing using technologies such as CUDA
and FPGAs. He has been a C# MVP since 2009.
xi
About the Technical Reviewer
Massimo Nardone has more than 24 years
of experiences in Security, Web/Mobile
development, Cloud, and IT Architecture. His
true IT passions are Security and Android.
He has been programming and teaching
how to program with Android, Perl, PHP, Java,
VB, Python, C/C++, and MySQL for more than
20 years.
He holds a Master of Science degree in
Computing Science from the University of
Salerno, Italy.
He has worked as a Project Manager, Software Engineer, Research
Engineer, Chief Security Architect, Information Security Manager, PCI/SCADA
Auditor, and Senior Lead IT Security/Cloud/SCADA Architect for many years.
Technical skills include: Security, Android, Cloud, Java, MySQL,
Drupal, Cobol, Perl, Web and Mobile development, MongoDB, D3,
Joomla, Couchbase, C/C++, WebGL, Python, Pro Rails, Django CMS, Jekyll,
Scratch, etc.
He worked as visiting lecturer and supervisor for exercises at the
Networking Laboratory of the Helsinki University of Technology (Aalto
University). He holds four international patents (PKI, SIP, SAML, and Proxy
areas).
He currently works as Chief Information Security Office for Cargotec
Oyj and he is a member of ISACA Finland Chapter Board.
Massimo has reviewed more than 45 IT books for different publishers,
and coauthored Pro JPA 2 in Java EE 8 (Apress, 2018) and Pro Android
Games (Apress, 2015).
xiii
CHAPTER 1
Introduction
The topic of Design Patterns sounds dry, academically constipated and,
in all honesty, done to death in almost every programming language
imaginable—including programming languages such as JavaScript that
aren’t even properly OOP! So why another book on it?
I guess the main reason this book exists is that C++ is great again. After
a long period of stagnation, it’s now evolving, growing, and despite the
fact that it has to contend with backwards C compatibility, good things are
happening, albeit not at the pace we’d all like. (I’m looking at modules,
among other things.)
Now, on to Design Patterns—we shouldn’t forget that the original
Design Patterns book1 was published with examples in C++ and Smalltalk.
Since then, plenty of programming languages have incorporated
design patterns directly into the language: for example, C# directly
incorporated the Observer pattern with its built-in support for events
(and the corresponding event keyword). C++ has not done the same, at
least not on the syntax level. That said, the introduction of types such as
std::function sure made things a lot simpler for many programming
scenarios.
1
rich Gamma et al., Design Patterns: Elements of Reusable Object-Oriented
E
Software (Boston, MA: Addison Wesley, 1994).
Preliminaries
Who This Book Is For
This book is designed to be a modern-day update to the classic GoF book,
targeting specifically the C++ programming language. I mean, how many
of you are writing Smalltalk out there? Not many; that would be my guess.
The goal of this book is to investigate how we can apply Modern C++
(the latest versions of C++ currently available) to the implementations of
classic design patterns. At the same time, it’s also an attempt to flesh out
any new patterns and approaches that could be useful to C++ developers.
Finally, in some places, this book is quite simply a technology demo for
Modern C++, showcasing how some of its latest features (e.g., coroutines)
make difficult problems a lot easier to solve.
2
Chapter 1 Introduction
3
Chapter 1 Introduction
You should be aware that most of the examples leverage Modern C++
(C++11, 14, 17 and beyond) and generally use the latest C++ language
features that are available to developers. For example, you won’t find
many function signatures ending in -> decltype(...) when C++14
lets us automatically infer the return type. None of the examples target
a particular compiler, but if something doesn’t work with your chosen
compiler,2 you’ll need to find workarounds.
At certain points in time, I will be referencing other programming
languages such as C# or Kotlin. It’s sometimes interesting to note how
designers of other languages have implemented a particular feature. C++
is no stranger to borrowing generally available ideas from other languages:
for example, the introduction of auto and type inference on variable
declarations and return types is present in many other languages.
2
Intel, I’m looking at you!
4
Chapter 1 Introduction
Piracy
Digital piracy is an inescapeable fact of life. A brand new generation is
growing up right now that has never purchased a movie or a book—even
this book. There’s not much that can be done about this. The only thing
I can say is that if you pirated this book, you might not be reading the latest
version.
The joy of online digital publishing is I get to update the book as new
versions of C++ come out and I do more research. So if you paid for this
book, you’ll get free updates in the future as new versions of the C++
language and the Standard Library are released. If not… oh, well.
Important Concepts
Before we begin, I want to briefly mention some key concepts of the C++
world that are going to be referenced in this book.
Now, you might be wondering why one would ever do that? Well,
one reason is to be able to access a typed this pointer inside a base class
implementation.
5
Chapter 1 Introduction
M
ixin Inheritance
In C++, a class can be defined to inherit from its own template argument,
for example:
6
Chapter 1 Introduction
Properties
A property is nothing more than a (typically private) field and a combination
of a getter and a setter. In standard C++, a property looks as follows:
1 class Person
2 {
3 int age;
4 public:
5 int get_age() const { return age; }
6 void set_age(int value) { age = value; }
7 };
1 class Person
2 {
3 int age_;
4 public:
5 int get_age() const { return age_; }
6 void set_age(int value) { age_ = value; }
7 __declspec(property(get=get_age, put=set_age)) int age;
8 };
1 Person person;
2 p.age = 20; // calls p.set_age(20)
7
Chapter 1 Introduction
1 struct Journal
2 {
3 string title;
4 vector<string> entries;
5
6 explicit Journal(const string& title) : title{title} {}
7 };
8
Chapter 1 Introduction
Now, you could add functionality for adding an entry to the journal,
prefixed by the entry’s ordinal number in the journal. This is easy:
9
Chapter 1 Introduction
1 struct PersistenceManager
2 {
3 static void save(const Journal& j, const string& filename)
4 {
5 ofstream ofs(filename);
6 for (auto& s : j.entries)
7 ofs << s << endl;
8 }
9 };
10
Chapter 1 Introduction
Open-Closed Principle
Suppose we have an (entirely hypothetical) range of products in a
database. Each product has a color and size and is defined as:
1 struct ProductFilter
2 {
3 typedef vector<Product*> Items;
4 };
11
Chapter 1 Introduction
Our current approach of filtering items by color is all well and good.
Our code goes into production but, unfortunately, some time later the boss
comes in and asks us to implement filtering by size, too. So we jump back
into ProductFilter.cpp, add the following code and recompile:
This feels like outright duplication, doesn’t it? Why don’t we just write
a general method that takes a predicate (some function)? Well, one reason
could be that different forms of filtering can be done in different ways: for
example, some record types might be indexed and need to be searched in
a specific way; some data types are amenable to search on a GPU, while
others are not.
12
Chapter 1 Introduction
Our code goes into production but, once again, the boss comes back
and tells us that now there’s a need to search by both color and size. So
what are we to do but add another function?
1 ProductFilter::Items ProductFilter::by_color_and_size(Items
2 items, Size size, Color color)
3 {
4 Items result;
5 for (auto& i : items)
6 if (i->size == size && i->color == color)
7 result.push_back(i);
8 return result;
9 }
13
Chapter 1 Introduction
Again, all we are doing is specifying the signature for a function called
filter which takes all the items and a specification, and returns all items
that conform to the specification. There is an assumption that the items
are stored as a vector<T*>, but in reality you could pass filter() either
a pair of iterators or some custom-made interface designed specifically
for going through a collection. Regrettably, the C++ language has failed to
standardize the notion of an enumeration or collection, something that
exists in other programming languages (e.g., .NET’s IEnumerable).
Based on the preceding, the implementation of an improved filter is
really simple:
14
Chapter 1 Introduction
10 result.push_back(p);
11 return result;
12 }
13 };
Armed with this specification, and given a list of products, we can now
filter them as follows:
15
Chapter 1 Introduction
8 ColorSpecification green(Color::Green);
9
10 auto green_things = bf.filter(all, green);
11 for (auto& x : green_things)
12 cout << x->name << " is green" << endl;
The preceding gets us “Apple” and “Tree” because they are both green.
Now, the only thing we haven’t implemented so far is searching for size
and color (or, indeed, explained how you would search for size or color,
or mix different criteria). The answer is that you simply make a composite
specification. For example, for the logical AND, you can make it as follows:
16
Another Random Scribd Document
with Unrelated Content
Æquitas non vaga atque incerta est, sed terminos habet atque
limites præfinitas.
Equity is not vague and uncertain, but has determinate
or prescribed boundaries and limits.
Æquitas vult domum quod alteri obsit ex causa æque favorabili esse
ac id quod aufert.
Equity wishes that the house which may be injurious to
another should be in the predicament, equally
favourable to that other, as that which it takes from
him.
Æquitas vult spoliatos, vel deceptos, vel lapsos ante omnia restituti.
Equity wishes the spoiled, the deceived, and the
ruined, above all things to have restitution.
Aliquis non debet esse judex in propria causa; quia non potest esse
judex et pars.
One ought not to be judge in his own cause, because
he cannot be a judge and a party.
Ambigua autem intentio ita accipienda est, ut res salva actori sit.
An ambiguous answer is so to be understood that the
interest of the pleader may be safe.
Caveat emptor; qui ignorare non debuit quod jus alienum emit.
Let the purchaser take care; who ought not to be
ignorant what right of another he purchases.
Confirmare est id quod prius infirmum fuit, firmare vel firmum facere.
To confirm is to strengthen, or make strong, that which
before was weak.
Confirmatio est possessionis jure defective per eos quorum jus est
ratihabitio.
The confirmation of a possession defective in law, is a
ratification by means of those whose right it is.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com