-
Notifications
You must be signed in to change notification settings - Fork 11
/
example4.cpp
67 lines (55 loc) · 1.45 KB
/
example4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Resource
{
Resource(char* byte) : byte_(byte) {}
char* byte() const { return byte_; }
virtual string name() const = 0;
~Resource() { delete byte_; }
protected:
char* byte_ = nullptr;
};
struct ResourceA : Resource
{
ResourceA(char* byte) : Resource(byte) {}
string name() const override { return string("ResourceA ").append(byte_); }
};
struct ResourceB : Resource
{
ResourceB(char* byte) : Resource(byte) {}
string name() const override { return 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)
{
cout << res->name() << endl;
}
}
private:
vector<Resource*> resources;
};
int main()
{
ResourceCollection collection;
ResourceFactory rf;
collection.add(rf.makeResourceA(new char{0x01}));
collection.add(rf.makeResourceB(new char{0x02}));
collection.printAll();
auto firstByte = collection[0]->byte();
collection.clear();
cout << *firstByte << endl;
return 0;
}