C++ features by examples
patterns.cpp
Go to the documentation of this file.
1
#include <bits/stdc++.h>
2
3
using namespace
std;
4
66
template
<
typename
ValueType>
67
struct
Setter_interface
{
69
virtual
void
set
(ValueType i) = 0;
70
virtual
~Setter_interface
() =
default
;
71
};
72
73
template
<
typename
ValueType>
74
struct
Getter_interface
{
76
virtual
ValueType
get
()
const
= 0;
77
virtual
~Getter_interface
() =
default
;
78
};
79
80
template
<
typename
ValueType>
81
struct
Change_interface
{
83
virtual
void
change
(ValueType c) = 0;
84
virtual
~Change_interface
() =
default
;
85
};
86
87
template
<
typename
ValueType>
88
class
Synchronised_encapsulated_value
94
:
public
Setter_interface
<ValueType>,
public
Getter_interface
<ValueType>,
public
Change_interface
<ValueType>
95
{
96
void
set(ValueType i)
override
{
97
scoped_lock writer_lock(mtx);
98
value = i;
99
}
100
101
ValueType get()
const override
{
102
shared_lock reader_lock(mtx);
103
return
value;
104
}
105
106
void
change(ValueType c)
override
{
107
scoped_lock writer_lock(mtx);
108
value += c;
109
}
110
111
mutable
shared_mutex mtx;
112
ValueType value;
113
};
114
115
void
oop_demo
()
121
{
122
auto
client = [] (
Setter_interface<int>
& s,
Getter_interface<int>
& g) {
123
s.
set
(1);
124
assert(g.get() == 1);
125
};
126
Synchronised_encapsulated_value<int>
v;
127
Setter_interface<int>
& s = v;
128
Getter_interface<int>
& g = v;
129
client(s, g);
130
131
auto
client2 = [] (
Setter_interface<string>
& s,
Getter_interface<string>
& g) {
132
s.
set
(
"abc"
);
133
assert(g.
get
() ==
"abc"
);
134
};
135
Synchronised_encapsulated_value<string>
v2;
136
Setter_interface<string>
& s2(v2);
137
Getter_interface<string>
& g2(v2);
138
Change_interface<string>
& c2(v2);
139
client2(s2, g2);
140
c2.
change
(
"de"
);
141
assert(g2.
get
() ==
"abcde"
);
142
}
143
145
165
struct
Interface
167
{
168
virtual
int
method
() = 0;
169
virtual
~Interface
() =
default
;
170
};
171
186
#define SINGLETON(Singleton) \
187
public: \
188
/* Meyers Singleton realization */
\
189
static Singleton& instance() { \
190
static Singleton me; \
191
return me; \
192
} \
193
Singleton(const Singleton&) = delete; \
194
Singleton& operator=(const Singleton&) = delete; \
195
Singleton(Singleton&&) = delete; \
196
Singleton& operator=(Singleton&&) = delete; \
197
private: \
198
Singleton()
199
200
struct
Singleton_demo
201
{
202
SINGLETON
(
Singleton_demo
) { };
203
};
204
205
struct
Factory_method_demo
206
{
207
virtual
unique_ptr<Interface>
factory_method
() = 0;
208
209
int
client
() {
210
auto
p(
factory_method
());
211
return
p->method();
212
};
213
};
214
215
struct
Sample_product
216
:
Interface
217
{
218
int
data
;
219
int
method
()
override
{
return
data
; }
220
Sample_product
(
int
d = 0) :
data
(d) {}
221
};
222