DEV Community

Cover image for Three Design Patterns, Four Birds: Factory, Builder and Strategy in C++
Japnoor Kaur Manku
Japnoor Kaur Manku

Posted on

Three Design Patterns, Four Birds: Factory, Builder and Strategy in C++

Design patterns can feel abstract until you need one. For a software design project at the University of Lethbridge, I built a small bird simulator in C++ and used three classic patterns. Each one solved a specific problem I'd otherwise have solved with a pile of if statements.

What it simulates

Four species from two regions, each going through the seasons:

Bird Region Type
Golden Eagle North America eagle
White-tailed Eagle Europe eagle
Kea New Zealand parrot
Kākāriki New Zealand parrot

Each bird builds a nest from its own materials and does something different in spring, summer, fall and winter. A golden eagle courts in spring, raises chicks in summer and migrates in fall. A kea moves to lower altitudes to forage in fall and scavenges through winter.

All of that comes from a JSON file, not from the code:

{
  "type": "eagle",
  "name": "Golden Eagle",
  "region": "North America",
  "nestMaterials": ["Twigs", "Grass", "Feathers"],
  "migration": { "Spring": "Alaska", "Fall": "Mexico" },
  "behaviors": {
    "Spring": "EagleSpringBehavior",
    "Summer": "EagleSummerBehavior",
    "Fall": "EagleFallBehavior",
    "Winter": "EagleWinterBehavior"
  }
}
Enter fullscreen mode Exit fullscreen mode

Adding a fifth bird of an existing type is a JSON edit, with no recompiling.

Pattern 1: Factory, for creating the right kind of bird

Problem: the program reads a list of birds from JSON and has to create the right kind of object for each one.

Solution: a factory per bird family. main picks the factory from the type field, and the factory knows how to build that family from the JSON:

if (birdData["type"] == "eagle") {
    factory = new EagleFactory();
} else if (birdData["type"] == "parrot") {
    factory = new ParrotFactory();
} else {
    throw std::runtime_error("Unknown bird type: " +
        birdData["type"].get<std::string>());
}
birds.push_back(factory->createBird(birdData));
Enter fullscreen mode Exit fullscreen mode

The rest of the program never needs to know the concrete classes. It only works with Bird*.

Pattern 2: Builder, for putting a nest together

Problem: nests are built step by step from a variable list of materials.

Solution: a NestBuilder interface with an addMaterial() step and a concrete builder that assembles the result. Each bird calls buildNest(&builder) and feeds in its own materials. The bird decides what goes in; the builder decides how a nest is assembled.

Pattern 3: Strategy, for changing behaviour by season

Problem: every bird behaves differently in every season. Written naively, that's a big switch on bird type nested inside a switch on season, and it grows every time you add either.

Solution: each behaviour is its own small class with a shared interface:

class SeasonalBehavior {
 public:
    virtual void execute(const std::string& birdName) = 0;
    virtual ~SeasonalBehavior() = default;
};

class EagleFallBehavior : public SeasonalBehavior {
 public:
    void execute(const std::string& birdName) override {
        std::cout << birdName << " begins migration to warmer climates.\n";
    }
};
Enter fullscreen mode Exit fullscreen mode

Each bird holds a map from season to strategy, and the simulation loop stays small:

std::vector<std::string> seasons = {"Spring", "Summer", "Fall", "Winter"};

for (auto bird : birds) {
    for (const auto& season : seasons) {
        bird->performSeasonalActivity(season);
        if (season == "Spring") {
            bird->buildNest(&builder);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

A new behaviour means a new class. Nothing existing has to change. That's the open/closed principle in practice.

What I'd improve

Looking back at this code as a fourth-year student, a few things stand out:

  • Use smart pointers. Birds and factories are created with new and deleted by hand. std::unique_ptr would make the ownership clear and remove the risk of leaks if an exception is thrown halfway through.
  • Don't hard-code file paths. main opens the config from an absolute path on the lab machine I developed on. It should take the path as a command-line argument.
  • A registry instead of if/else for factories. A std::map<std::string, std::function<...>> from type name to factory would let new bird families register themselves.

Takeaway

The patterns weren't the point of the assignment for me so much as the habit behind them: when you see a growing if/else or switch, ask whether each branch should be its own object.

Code is on GitHub.

Top comments (0)