Подробнее на 👉 refactoring.guru
#include <iostream>
#include <vector>
// Интерфейс итератора
class Iterator {
public:
virtual bool hasNext() const = 0;
virtual std::string next() = 0;
};
// Интерфейс коллекции, по которой можно итерироваться
class IterableCollection {
public:
virtual Iterator* createIterator() const = 0;
};
// Конкретный итератор
class ConcreteIterator : public Iterator {
private:
const std::vector<std::string>& data;
size_t currentIndex;
public:
ConcreteIterator(const std::vector<std::string>& data)
: data(data), currentIndex(0) {}
bool hasNext() const override { return currentIndex < data.size(); }
std::string next() override { return data[currentIndex++]; }
};
// Конкретная коллекция
class ConcreteCollection : public IterableCollection {
private:
std::vector<std::string> cars;
public:
void addCar(const std::string& car) { cars.push_back(car); }
Iterator* createIterator() const override {
return new ConcreteIterator(cars);
}
};
int main() {
ConcreteCollection carCollection;
carCollection.addCar("Audi");
carCollection.addCar("BMW");
carCollection.addCar("Mercedes");
Iterator* iterator = carCollection.createIterator();
while (iterator->hasNext()) {
std::cout << iterator->next() << std::endl;
}
delete iterator;
return 0;
}
Будет напечатано:
Audi BMW Mercedes
class Iterator {
bool hasNext() => false;
String next() => '';
}
class IterableCollection {
Iterator createIterator() => Iterator();
}
class ConcreteIterator implements Iterator {
final List<String> data;
int currentIndex = 0;
ConcreteIterator(this.data);
bool hasNext() => currentIndex < data.length;
String next() => data[currentIndex++];
}
class ConcreteCollection implements IterableCollection {
final List<String> cars = [];
void addCar(String car) {
cars.add(car);
}
Iterator createIterator() => ConcreteIterator(cars);
}
void main() {
var carCollection = ConcreteCollection();
carCollection.addCar('Audi');
carCollection.addCar('BMW');
carCollection.addCar('Mercedes');
var iterator = carCollection.createIterator();
while (iterator.hasNext()) {
print(iterator.next());
}
}
Будет напечатано:
Audi BMW Mercedes