-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNullObject.cpp
More file actions
68 lines (60 loc) · 1.7 KB
/
NullObject.cpp
File metadata and controls
68 lines (60 loc) · 1.7 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
/**
* \file NullObject.cpp
* \brief Object with no referenced value or with defined neutral (null) behavior
*
* Null object creates a special object to mean nothing/null/absent/default.
* It means that the default behaviour can be implementer in the null object
* instead of making an explicit check for null, or using NULL pointers.
*
* \see https://en.wikipedia.org/wiki/Null_object_pattern
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//--------------------------------------------------------------------------------------------------
class IRecipient
{
public:
virtual ~IRecipient() = default;
virtual std::string name() const = 0;
};
//--------------------------------------------------------------------------------------------------
class NullRecipient final :
public IRecipient
{
public:
std::string name() const override
{
return "[n/a]";
}
};
//--------------------------------------------------------------------------------------------------
class World :
public IRecipient
{
public:
std::string name() const override
{
return "world";
}
};
//--------------------------------------------------------------------------------------------------
void
helloWorld(
const IRecipient &a_recipient = NullRecipient()
)
{
std::cout << "Hello " << a_recipient.name() << "!" << std::endl;
}
//--------------------------------------------------------------------------------------------------
int main(int, char **)
{
::helloWorld( World() );
::helloWorld();
return EXIT_SUCCESS;
}
//--------------------------------------------------------------------------------------------------
#if OUTPUT
"Hello world!"
"Hello [n/a]!"
#endif