before.cxx
#include <string>
#include <iostream>
class ACounter {
public:
unsigned int count(const std::string &input) {
unsigned int count = 0;
for (int i = 0; i < input.length(); ++i) {
if (input[i] == 'a' || input[i] == 'A') {
++count;
}
}
return count;
}
};
class BCounter {
public:
unsigned int count(const std::string &input) {
unsigned int count = 0;
for (int i = 0; i < input.length(); ++i) {
if (input[i] == 'b' || input[i] == 'B') {
++count;
}
}
return count;
}
};
ACounter aCounter;
BCounter bCounter;
void displayNumberOfA(const std::string &input) {
std::cout << "the number of a/A is " << aCounter.count(input) << std::endl;
}
void displayNumberOfB(const std::string &input) {
std::cout << "the number of b/B is " << bCounter.count(input) << std::endl;
}
int main(void) {
displayNumberOfA("abAAB");
displayNumberOfB("abABB");
return 0;
}
after.cxx
#include <string>
#include <iostream>
#include <map>
class Counter {
public:
virtual unsigned int count(const std::string &input) = 0;
};
class ACounter: public Counter {
public:
unsigned int count(const std::string &input) {
unsigned int count = 0;
for (int i = 0; i < input.length(); ++i) {
if (input[i] == 'a' || input[i] == 'A') {
++count;
}
}
return count;
}
};
class BCounter: public Counter {
public:
unsigned int count(const std::string &input) {
unsigned int count = 0;
for (int i = 0; i < input.length(); ++i) {
if (input[i] == 'b' || input[i] == 'B') {
++count;
}
}
return count;
}
};
class CounterFactory {
public:
CounterFactory(void) {
counterMap.insert(std::make_pair('A', new ACounter));
counterMap.insert(std::make_pair('B', new BCounter));
}
Counter &getCounter(char counterType) {
return *counterMap.find(counterType)->second;
}
private:
std::map<char, Counter *> counterMap;
};
CounterFactory counterFactory;
void displayNumberOfA(const std::string &input) {
Counter &aCounter = counterFactory.getCounter('A');
std::cout << "the number of a/A is " << aCounter.count(input) << std::endl;
}
void displayNumberOfB(const std::string &input) {
Counter &bCounter = counterFactory.getCounter('B');
std::cout << "the number of b/B is " << bCounter.count(input) << std::endl;
}
int main(void) {
displayNumberOfA("abAAB");
displayNumberOfB("abABB");
return 0;
}