-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathConceptualExample03.cpp
More file actions
88 lines (71 loc) · 2.6 KB
/
Copy pathConceptualExample03.cpp
File metadata and controls
88 lines (71 loc) · 2.6 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// ===========================================================================
// ConceptualExample03.cpp // Factory Method / No Inheritance
// ===========================================================================
#include <string_view>
#include <memory>
#include <print>
#include <unordered_map>
#include <functional>
namespace ConceptualExample03
{
// We describe the products still as an interface to allow for client-side polymorphism.
class ProductBase
{
public:
virtual ~ProductBase() = default;
[[nodiscard]]
virtual std::string_view getName() const = 0;
};
class ConcreteProductA : public ProductBase
{
public:
[[nodiscard]]
std::string_view getName() const override { return "Product A"; }
};
class ConcreteProductB : public ProductBase
{
public:
[[nodiscard]]
std::string_view getName() const override { return "Product B"; }
};
// =======================================================================
class FunctionalFactory
{
public:
// We register function objects (lambdas) instead of factory classes.
using CreatorMethod = std::function<std::unique_ptr<ProductBase>()>;
void registerType(std::string_view typeName, CreatorMethod creator) {
m_registry[std::string(typeName)] = std::move(creator);
}
[[nodiscard]]
std::unique_ptr<ProductBase> createProduct(std::string_view typeName) const {
auto it = m_registry.find(std::string(typeName));
if (it != m_registry.end()) {
return it->second(); // Calls the lambda
}
return nullptr;
}
private:
std::unordered_map<std::string, CreatorMethod> m_registry;
};
}
void test_conceptual_example_03()
{
using namespace ConceptualExample03;
FunctionalFactory factory;
// registration takes place inline via lambda – no "FactoryA" class required!
factory.registerType("A", []() { return std::make_unique<ConcreteProductA>(); });
factory.registerType("B", []() { return std::make_unique<ConcreteProductB>(); });
// client code simply uses the factory via ID/string.
auto prod1 = factory.createProduct("A");
auto prod2 = factory.createProduct("B");
if (prod1) {
std::println("Created: {}", prod1->getName());
}
if (prod2) {
std::println("Created: {}", prod2->getName());
}
}
// ===========================================================================
// End-of-File
// ===========================================================================