Created
August 16, 2019 12:27
-
-
Save plusangel/18b134d1a9afa22f2506f0cd2b43f0e5 to your computer and use it in GitHub Desktop.
abstract, interfaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class Switchable { | |
public: | |
virtual void on() = 0; | |
virtual void off() = 0; | |
}; | |
class Switch { | |
private: | |
Switchable& switchable_; | |
bool state {false}; | |
public: | |
Switch(Switchable& switchable) : switchable_{switchable} | |
{} | |
void toggle() { | |
if (state) { | |
state = false; | |
switchable_.off(); | |
} else { | |
state = true; | |
switchable_.on(); | |
} | |
} | |
}; | |
class Lamp : public Switchable | |
{ | |
public: | |
void on() override { | |
std::cout << "Lamp is on\n"; | |
} | |
void off() override { | |
std::cout << "Lamp is off\n"; | |
} | |
}; | |
int main(int argc, char* argv[]) | |
{ | |
Lamp my_lamp; | |
Switch my_switch(my_lamp); | |
my_lamp.on(); | |
my_lamp.off(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment