ネタ元 → FizzBuzz>それDecoratorパターンで(改)
Decoratorパターンだとぅ?
そんじゃこちとらChain-of-Responsibilityパターンで:
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
class checker {
public:
virtual bool operator()(int n) const =0;
};
class holder {
checker* checker_;
public:
holder(checker* c) : checker_(c) {}
bool operator==(int n) const {
return checker_->operator()(n);
}
};
class fizzbuzz : public checker {
int mod_;
std::string str_;
public:
fizzbuzz(int m, std::string s) : mod_(m), str_(s) {}
virtual bool operator()(int n) const {
if ( n % mod_ ) {
return false;
}
std::cout << str_ << '(' << n << ") " << std::flush;
return true;
}
};
int main() {
std::vector<holder> vec;
fizzbuzz first(15,"FizzBuzz");
vec.push_back(holder(&first));
fizzbuzz second(3,"Fizz");
vec.push_back(holder(&second));
fizzbuzz third(5,"Buzz");
vec.push_back(holder(&third));
for ( int i = 1; i <= 100; ++i ) {
if ( std::find(vec.begin(), vec.end(), i) == vec.end() ) {
std::cout << i << ' ' << std::flush;
}
}
}