Skip to content

Commit 4d9484c

Browse files
author
sajith
committed
Improved
1 parent 36bb1e5 commit 4d9484c

File tree

2 files changed

+89
-1
lines changed

2 files changed

+89
-1
lines changed

CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,5 @@ add_subdirectory(plant-care-better)
2828
#add_executable(isp_device_better ISP/isp_device_example_better.cpp)
2929
#add_executable(isp_multiple_inheritance ISP/isp_multiple_inheritance.cpp)
3030
#add_executable(dip_lamp DIP/dip_lamp_example.cpp)
31-
add_executable(dip_lamp_better DIP/dip_lamp_example_better.cpp)
31+
#add_executable(dip_lamp_better DIP/dip_lamp_example_better.cpp)
32+
add_executable(dip_lamp_better2 DIP/dip_lamp_example_better2.cpp)

DIP/dip_lamp_example_better2.cpp

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
//
2+
// Created by sajith on 4/23/21.
3+
//
4+
5+
#include <iostream>
6+
7+
8+
template<typename T> concept Switchable =
9+
requires(T t)
10+
{
11+
t.switchOn();
12+
t.switchOff();
13+
};
14+
15+
// This is our explicit abstraction
16+
17+
// Client module, policy, higher layer
18+
template<typename Switchable>
19+
class Button
20+
{
21+
Switchable &switchable;
22+
bool on = false;
23+
24+
public:
25+
Button(Switchable &switchable) : switchable{switchable} {}
26+
27+
void toggle()
28+
{
29+
if (on)
30+
{
31+
switchable.switchOff();
32+
} else
33+
{
34+
switchable.switchOn();
35+
}
36+
37+
on = !on;
38+
}
39+
};
40+
41+
42+
// service module, implementation details, lower layer
43+
44+
class Lamp1
45+
{
46+
public:
47+
void switchOn()
48+
{
49+
std::cout << "Lamp1 is on\n";
50+
}
51+
52+
void switchOff()
53+
{
54+
std::cout << "Lamp1 is off\n";
55+
}
56+
};
57+
58+
class Lamp2
59+
{
60+
public:
61+
void switchOn()
62+
{
63+
std::cout << "Lamp2 is on\n";
64+
}
65+
66+
void switchOff()
67+
{
68+
std::cout << "Lamp2 is off\n";
69+
}
70+
};
71+
72+
73+
int main()
74+
{
75+
Lamp1 lamp1;
76+
Button<Lamp1> button1(lamp1);
77+
button1.toggle();
78+
button1.toggle();
79+
80+
Lamp2 lamp2;
81+
Button<Lamp2> button2(lamp2);
82+
button2.toggle();
83+
button2.toggle();
84+
85+
return 0;
86+
}
87+

0 commit comments

Comments
 (0)