- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactory.cpp
More file actions
Latest commit
54 lines (46 loc) · 1.21 KB
/
Copy pathfactory.cpp
File metadata and controls
54 lines (46 loc) · 1.21 KB
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
/*
A factory pattern design using map, lambdas and polymorphism
https://ideone.com/Bj51fT
*/
#include<map>
#include<functional>
#include<iostream>
#include<string>
classBase
{
public:
virtual~Base() = default;
virtual std::string whatBaseAmI() = 0;
virtualunsignedlongtoDec() = 0;
};
classHex : publicBase
{
std::string _number;
public:
Hex(std::string number) : _number(number) {}
unsignedlongtoDec() override { returnstd::strtoul(_number.c_str(), NULL, 16); }
std::string whatBaseAmI() override { return"Hex"; }
};
classBinary : publicBase
{
std::string _number;
public:
Binary(std::string number) : _number(number) {}
unsignedlongtoDec() override { returnstd::strtoul(_number.c_str(), NULL, 2); }
std::string whatBaseAmI() override { return"Binary"; }
};
intmain()
{
std::map<std::string, std::function<Base *(std::string const &)>> factory =
{
{ "Binary", [](std::string const &number) { returnnewBinary(number); } },
{ "Hex", [](std::string const &number) { returnnewHex(number); } }
};
Base *b = factory["Binary"]("1001001001001");
if (b)
{
std::cout << "Base: " << b->whatBaseAmI() << std::endl;
std::cout << "Decimal Value: " << b->toDec() << std::endl;
}
return0;
}