Data structures & design patterns
Indexing and the cost of loops, a linked list built pointer by pointer, and two creational patterns — singleton and factory — in C++ and Python.
Data structures decide how data sits in memory; design patterns decide how objects come into existence. This course covers both at the level of the pointers involved, because that is where the bugs live.
It starts with indexing — how a 2D matrix is really a flat strip, and what a triple loop over it costs in Python. Then a singly linked list, where every operation is a matter of rewiring one or two pointers. The last two lessons use the code in the oop_design_patterns folder: a singleton, which guarantees one instance of a class, and a factory, which decides which class to build so the caller does not have to.
Every lesson has a live animation. The pattern lessons also run the repository’s programs under AddressSanitizer and with extra warnings, and report what that finds — leaks, a missing virtual destructor and a race — with fixes that were compiled and checked.
Prerequisites
- Classes, pointers and
new/deletein C++ (see the C++ course). - Basic Python and NumPy for the first lesson.
Running the code
cd oop_design_patterns/cpp
g++ -std=c++17 -Wall -Wextra 02_factory.cpp -o factory && ./factory
cd singleton && g++ main.cpp singleton.cpp -o main && ./main
python3 ../../python/01_singleton.py
To see memory errors as they happen, add -g -fsanitize=address to any of the C++ builds.
Lessons
- 1 Indexing and the triple loopA matrix is a flat strip of numbers. Multiplying two by hand in Python shows how indices map to memory — and what n³ loop iterations cost.
- 2 A singly linked listNodes scattered across the heap, held together by one pointer each. Insert, delete and reverse are all a matter of rewiring.
- 3 The singleton patternOne instance, created on first use — in C++ and Python, including the race that lets two instances slip through and the one-line fix.
- 4 The factory patternLet one function decide which class to build. Plus what AddressSanitizer and two warning flags find in the repository's version, and a fix.