-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactory.cpp
More file actions
54 lines (46 loc) · 1.21 KB
/
factory.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>
class Base
{
public:
virtual ~Base() = default;
virtual std::string whatBaseAmI() = 0;
virtual unsigned long toDec() = 0;
};
class Hex : public Base
{
std::string _number;
public:
Hex(std::string number) : _number(number) {}
unsigned long toDec() override { return std::strtoul(_number.c_str(), NULL, 16); }
std::string whatBaseAmI() override { return "Hex"; }
};
class Binary : public Base
{
std::string _number;
public:
Binary(std::string number) : _number(number) {}
unsigned long toDec() override { return std::strtoul(_number.c_str(), NULL, 2); }
std::string whatBaseAmI() override { return "Binary"; }
};
int main()
{
std::map<std::string, std::function<Base *(std::string const &)>> factory =
{
{ "Binary", [](std::string const &number) { return new Binary(number); } },
{ "Hex", [](std::string const &number) { return new Hex(number); } }
};
Base *b = factory["Binary"]("1001001001001");
if (b)
{
std::cout << "Base: " << b->whatBaseAmI() << std::endl;
std::cout << "Decimal Value: " << b->toDec() << std::endl;
}
return 0;
}