-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory_pattern.cpp
51 lines (40 loc) · 1.13 KB
/
factory_pattern.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
#include <typeinfo>
#include <memory>
#include <map>
#include <functional>
#include <string>
#include <string_view>
#include <iostream>
using namespace std::string_literals;
class Image {};
class BitmapImage : public Image {};
class PngImage : public Image {};
class JpgImage : public Image {};
struct IImageFactory
{
virtual std::unique_ptr<Image> Create(std::string_view type) = 0;
};
struct ImageFactory : public IImageFactory
{
virtual std::unique_ptr<Image> Create(std::string_view type) override
{
static std::map<std::string, std::function<std::unique_ptr<Image>()>> mapping
{
{ "bmp", []() {return std::make_unique<BitmapImage>(); } },
{ "png", []() {return std::make_unique<PngImage>(); } },
{ "jpg", []() {return std::make_unique<JpgImage>(); } }
};
auto it = mapping.find(type.data());
if (it != mapping.end())
{
std::cout<< "found "<< it->first<<std::endl;
return it->second();
}
return nullptr;
}
};
int main()
{
auto factory = ImageFactory{};
auto image = factory.Create("png");
};