1 Star 0 Fork 0

Tzewa Lam/DesignPatternsInCpp

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.cpp 1.61 KB
一键复制 编辑 原始数据 按行查看 历史
Tzewa Lam 提交于 2024-07-25 17:13 +08:00 . added 桥接模式
#include <iostream>
#include <memory>
class TV {
public:
virtual void on() = 0;
virtual void off() = 0;
virtual void switchChannel() = 0;
virtual ~TV() {}
};
class SonyTV : public TV {
public:
void on() {
std::cout << "Sony TV is ON" << std::endl;
}
void off() {
std::cout << "Sony TV is OFF" << std::endl;
}
void switchChannel() {
std::cout << "Switching Sony TV channel" << std::endl;
}
};
class TCLTV : public TV {
public:
void on() {
std::cout << "TCL TV is ON" << std::endl;
}
void off() {
std::cout << "TCL TV is OFF" << std::endl;
}
void switchChannel() {
std::cout << "Switching TCL TV channel" << std::endl;
}
};
class Operation {
public:
Operation(TV *tv) : m_tv(std::move(tv)) {}
virtual void work() = 0;
virtual ~Operation() {}
protected:
std::unique_ptr<TV> m_tv;
};
class TurnOn : public Operation {
public:
TurnOn(TV *tv) : Operation(tv) {}
void work() override {
m_tv->on();
}
};
class TurnOff : public Operation {
public:
TurnOff(TV *tv) : Operation(tv) {}
void work() override {
m_tv->off();
}
};
class SwitchChannel : public Operation {
public:
SwitchChannel(TV *tv) : Operation(tv) {}
void work() override {
m_tv->switchChannel();
}
};
int main() {
int n;
std::cin >> n;
while (n--) {
int type, op;
std::cin >> type >> op;
TV *tv = nullptr;
if (type == 0) {
tv = new SonyTV;
} else if (type == 1) {
tv = new TCLTV;
}
std::unique_ptr<Operation> oper;
if (op == 2) {
oper.reset(new TurnOn(tv));
} else if (op == 3) {
oper.reset(new TurnOff(tv));
} else if (op == 4) {
oper.reset(new SwitchChannel(tv));
}
oper->work();
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/fingsinz/design-patterns-in-cpp.git
git@gitee.com:fingsinz/design-patterns-in-cpp.git
fingsinz
design-patterns-in-cpp
DesignPatternsInCpp
master

搜索帮助