design_patterns/11_facade.cpp
Yuki 596204675b
feat: Add Facade
Implemented a demo for the Facade.
2025-04-12 03:55:21 +08:00

67 lines
1.6 KiB
C++

#include <iostream>
#include <memory>
using namespace std;
class Projector {
int brightness;
public:
void set_brightness(int brightness) { this->brightness = brightness; }
int get_brightness() { return brightness; }
};
class Amplifier {
int volume;
string mode;
public:
Amplifier() : mode("Normal") {}
void set_volume(int volume) { this->volume = volume; }
int get_volumn() { return volume; }
void set_mode(const string& mode) { this->mode = mode; }
const string& get_mode() {return this->mode; }
};
class Player {
unique_ptr<Projector> pro;
unique_ptr<Amplifier> amp;
public:
Player(unique_ptr<Projector> p, unique_ptr<Amplifier> a) :
pro(move(p)), amp(move(a)) {}
void play(const string& movie) {
cout << "Play movie: " << movie
<< " brightness: " << pro->get_brightness()
<< " volume: " << amp->get_volumn()
<< " in " << amp->get_mode() << " mode." << endl;
}
};
class TheaterFacade {
public:
void play(const string& movie) {
auto pro = make_unique<Projector>();
auto amp = make_unique<Amplifier>();
pro->set_brightness(10);
amp->set_volume(10);
Player p(move(pro), move(amp));
p.play(movie);
}
};
int main() {
// Simply use without configure
TheaterFacade f;
f.play("CSAPP");
// You can still control the details
auto pro = make_unique<Projector>();
auto amp = make_unique<Amplifier>();
pro->set_brightness(20);
amp->set_volume(42);
amp->set_mode("Virtual Surround");
Player p(move(pro), move(amp));
p.play("CSAPP");
}