Design Pattern-Bridge === # 橋接模式(Bridge) * 為一種結構模式 * 使用時機 : * 兩個(或以上)獨立類別的維度相互作用時,舉例你有積木(圓形跟方形)、顏色(紅色根藍色)這樣如果要交互組合會額外產生4個類別,如再擴充會呈倍數成長 * 提升各類別的靈活性及降低繼承使用 * 目的 : * 抽象跟實作可以各自擴充,不會影響到對方 * 降低繼承的使用 * 優點 : * 抽象了一個對外的介面但不會暴露實際細節的實作 * 符合OCP對於client的部分公佈可使用的API,但不會影響到內部功能開發 * 符合SRP可專注於功能上的實作 * 缺點 : * 如果使用在高內聚的類別會使程式更加複雜 # Flow chart  # 電腦的運作是靠OS建立的,所以先建立一個OS類別 (Implementor) ```cpp= class os_system{ public: os_system(){}; ~os_system(){}; virtual void operation() = 0; }; ``` # 可以有Linux跟Windows的OS (ConcreteImplementor) ```cpp= class linux_system : public os_system{ public: void operation() override{ cout << "Setting linux system." << endl; } }; class windows_system : public os_system{ public: void operation() override { cout << "Setting windows system." << endl; } }; ``` # 建立一個電腦的類別 (Abstraction) ```cpp= class computer{ public: std::shared_ptr<os_system> os_system_config = nullptr; computer(){}; computer(std::shared_ptr<os_system> os_system_setting) : os_system_config(os_system_setting){}; ~computer(){}; virtual void operation() = 0; }; ``` # 可以有不同品牌的電腦(RefinedAbstraction) ```cpp= class Dell_computer : public computer{ public: Dell_computer(std::shared_ptr<os_system> &os_system_setup) : computer(os_system_setup){}; ~Dell_computer(){}; void operation() override{ cout << "Turn on Dell computer." << endl; os_system_config->operation(); } }; class Gigabyte_computer : public computer{ public: Gigabyte_computer(std::shared_ptr<os_system> &os_system_setup) : computer(os_system_setup){}; ~Gigabyte_computer(){}; void operation() override{ cout << "Turn on Gigabyte computer." << endl; os_system_config->operation(); } }; ``` # 來看結果吧 * 可以看到今天選定os_system後可直接放到computer內使用,這樣一條龍特定品牌的電腦系統設定即可完成。 ```cpp= int main(){ std::shared_ptr<os_system> os_setting = std::make_shared<linux_system>(); std::shared_ptr<computer> computer_product = std::make_shared<Dell_computer>(os_setting); computer_product->operation(); return 0; } ```  github : https://github.com/GU-Lin/Design_Pattern_Practice/tree/main/Structural/Bridge source : https://hypc-pub.github.io/design-patterns/patterns/bridge-pattern.html ###### tags : `Structural` `DesignPattern`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up