首页 > 代码库 > 桥接模式
桥接模式
桥接模式网上都讲得很复杂,我总结一下就是一句话:
如果多个维度变化,每个维度都有一个基类,嗯,就这样
#include <iostream> using namespace std; class Os { public: virtual void SetOs() = 0; }; class LinuxOs : public Os { public: void SetOs() { cout<< "set linux" << endl; } }; class WindowsOs : public Os { public: void SetOs() { cout<< "set windows" << endl; } }; class MacOs : public Os { public: void SetOs() { cout<< "set mac" << endl; } }; class Computer { public: Computer(Os* s) : os_(s) { } virtual ~Computer() { if (os_) { delete os_; } os_ = NULL; } public: virtual void InstallOs() = 0; protected: Os* os_; }; class DellComputer : public Computer { public: DellComputer(Os* s) : Computer(s) { } public: void InstallOs() { cout<< "DellComputer:" << endl; os_->SetOs(); } }; class MacComputer : public Computer{ public: MacComputer(Os* s) : Computer(s) { } public: void InstallOs() { cout<< "MacComputer:" << endl; os_->SetOs(); } }; class IbmComputer : public Computer{ public: IbmComputer(Os* s) : Computer(s) { } public: void InstallOs() { cout<< "IbmComputer:" << endl; os_->SetOs(); } };
#include "main.h" using namespace std; int main(int argc, char* argv[]) { Computer* c = new DellComputer(new WindowsOs); c->InstallOs(); Computer* c2 = new MacComputer(new MacOs); c2->InstallOs(); Computer* c3 = new IbmComputer(new LinuxOs); c3->InstallOs(); }
桥接模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。