trainings/AdvancedCppV2/Presentation/exercises/resourceFactory/resourceFactory.cpp

65 lines
1.5 KiB
C++

#include <iostream>
#include <vector>
#include <string>
struct Resource
{
Resource(char* byte) : byte_(byte) {}
char* byte() const { return byte_; }
virtual std::string name() const = 0;
~Resource() { delete byte_; }
protected:
char* byte_ = nullptr;
};
struct ResourceA : Resource
{
ResourceA(char* byte) : Resource(byte) {}
std::string name() const override { return std::string("ResourceA ").append(byte_); }
};
struct ResourceB : Resource
{
ResourceB(char* byte) : Resource(byte) {}
std::string name() const override { return std::string("ResourceB ").append(byte_); }
};
struct ResourceFactory
{
Resource* makeResourceA(char* byte) { return new ResourceA{byte}; }
Resource* makeResourceB(char* byte) { return new ResourceB{byte}; }
};
struct ResourceCollection
{
void add(Resource* r) { resources.push_back(r); }
void clear() { resources.clear(); }
Resource* operator[](int index) { return resources[index]; }
void printAll()
{
for (const auto & res : resources)
{
std::cout << res->name() << std::endl;
}
}
private:
std::vector<Resource*> resources;
};
int main()
{
ResourceCollection collection;
ResourceFactory rf;
collection.add(rf.makeResourceA(new char{91}));
collection.add(rf.makeResourceB(new char{92}));
collection.printAll();
auto firstByte = collection[0]->byte();
collection.clear();
std::cout << *firstByte << std::endl;
return 0;
}