vendredi 29 septembre 2023

How can I apply the strategy pattern to a set of derived classes?

I have been learning about the strategy pattern. I have seen it as a technique that allows you to write extra code for an existing class with minimal changes to the original class.

I would like to apply this technique in my code, but my code has a set of derived classes that I want to implement strategies for.

To make a concrete example. Let's say I have an empty Shape class, and two subclasses Rectangle (int width, int height) and Circle (int radius).

I would like to implement a serialization strategy pattern that can write a Shape out as a simple TOML file.

I can do it like this for a single shape:

class Rectangle; 

class SerializerStrategy {
public:
  virtual std::string serialize(const Rectangle& rectangle) = 0;
};

class TomlSerializer : public SerializerStrategy {
public:
  std::string serialize(const Rectangle& rectangle) override {
    return "[Rectangle]\n"
           "width = " + std::to_string(rectangle.getWidth()) + "\n"
           "height = " + std::to_string(rectangle.getHeight());
  }
};

But I cannot find any solution which would enable me to, for example, iterate over a vector of Shapes that may be rectangles or circles and serialize each one.

I have tried reading through a lot of related questions on stack overflow. I've written my own simplified example code out as an experiment. I have watched video lectures on C++. I have asked claude AI for example code. I didn't find a solution from any of these attempts.

Aucun commentaire:

Enregistrer un commentaire