Interfaces as Plugins
Completed
Write an interface class Transform { virtual string apply(const string&) const = 0; } with implementations Upper, Reverse and Repeat(k). Read a word and a pipeline of transforms, apply them in order, and print the result after each step.
Input
Line 1: a word. Line 2: n. Then n transforms (upper, reverse, repeat K).
Output
n lines.
Example
Input
abc 3 upper reverse repeat 2
Output
ABC CBA CBACBA
Editor
C++
Hints
Store the pipeline as a vector of base-class pointers.
Solution explanation
New transforms can be added without touching the pipeline code - the open/closed principle.
Show solution
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
class Transform {
public:
virtual ~Transform() = default;
virtual string apply(const string &s) const = 0;
};
class Upper : public Transform {
public:
string apply(const string &s) const override {
string r = s;
for (char &c : r) c = toupper(c);
return r;
}
};
class Reverse : public Transform {
public:
string apply(const string &s) const override { return string(s.rbegin(), s.rend()); }
};
class Repeat : public Transform {
public:
explicit Repeat(int k) : k_(k) {}
string apply(const string &s) const override {
string r;
for (int i = 0; i < k_; i++) r += s;
return r;
}
private:
int k_;
};
int main() {
string word;
int n;
cin >> word >> n;
vector<unique_ptr<Transform>> pipeline;
for (int i = 0; i < n; i++) {
string kind;
cin >> kind;
if (kind == "upper") pipeline.push_back(make_unique<Upper>());
else if (kind == "reverse") pipeline.push_back(make_unique<Reverse>());
else {
int k;
cin >> k;
pipeline.push_back(make_unique<Repeat>(k));
}
}
for (const auto &t : pipeline) {
word = t->apply(word);
cout << word << "\n";
}
return 0;
}