#include <iostream>
#include <string>
#include <memory>
#include <vector>
class IProduct {
public:
virtual std::string Name() = 0;
virtual bool Say() = 0;
virtual ~IProduct() {}
};
using Product = std::shared_ptr<IProduct>;
class IFactory {
public:
Product Create(const std::string& owner) {
Product p = CreateClass(owner);
RegisterClass(p);
return p;
}
virtual ~IFactory() {}
protected:
virtual Product CreateClass(const std::string&) = 0;
virtual void RegisterClass(Product p) = 0;
};
class A : public IProduct {
std::string owner;
public:
A(const std::string& owner) {
this->owner = owner;
}
std::string Name() {
return owner;
}
bool Say() {
std::cout << "Baw " << X << std::endl;
return true;
}
private:
int X = 123;
};
class B : public IProduct {
std::string owner;
public:
B(const std::string& owner) {
this->owner = owner;
}
std::string Name() {
return owner;
}
bool Say() {
std::cout << "Maw " << X << std::endl;
return true;
}
protected:
char X = 'b';
};
class ClassFactory : public IFactory {
std::vector<std::string> owners;
protected:
Product CreateClass(const std::string& owner) {
if (owner == "A")
return std::make_shared<A>(owner);
else if (owner == "B")
return std::make_shared<B>(owner);
else
return nullptr;
}
void RegisterClass(Product p) {
owners.push_back(p->Name());
}
};
int main()
{
auto factory = std::make_shared<ClassFactory>();
auto x = factory->Create("A");
std::cout << x->Name() << std::endl;
std::cout << std::boolalpha << x->Say() << std::endl;
auto y = factory->Create("B");
std::cout << y->Name() << std::endl;
std::cout << std::boolalpha << y->Say() << std::endl;
}