【设计模式】手机软件何时统一 ---- 桥接模式
一,概述
定义:将抽象部分与实现部分分离,使它们都可以独立的变化。
在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,那么如何应对这种“多维度的变化”?如何利用面向对象的技术来使得该类型能够轻松的沿着多个方向进行变化,而又不引入额外的复杂度?这就要使用Bridge模式。
【注意】C++中继承声明为 public
二,示例
两款手机,品牌M和品牌N,且每部手机都包含通讯录和游戏。
1)第一种实现
实现:
以手机品牌为抽象基类,手机品牌M、N继承手机品牌基类。
再分别实现M、N中的游戏和通讯录类。
最后用爷爷类:手机品牌, 创建孙子类通讯录M(N)和游戏M(N)
缺点:
如果再增加一个MP3类则需要在手机M 和手机N下面各自加一个子类(相似的子类)
如果添加一个手机品牌则需要添加更多的类
#include <iostream>using namespace std; class Implementor//各个小部件类(例如手机软件) { public: virtual void Operation()//多态虚函数一定要有实现(提供给虚函数表入口地址) { } }; class ConcreteImplementorA :public Implementor { public:void Operation() { cout<<"具体实现A的方法执行"<<endl; } }; class ConcreteImplementorB :public Implementor { public:void Operation() { cout<<"具体实现B的方法执行"<<endl; } }; class Abstraction //总的构成(类似手机品牌抽象类) { protected: Implementor *implementor; public: void SetImplementor(Implementor *implementor) { this->implementor = implementor; } virtual void Operation() { implementor->Operation(); } }; class RefinedAbstraction :public Abstraction { public: void Operation() { implementor->Operation(); } }; int main() { Abstraction *ab = new RefinedAbstraction(); ab->SetImplementor(new ConcreteImplementorA());//组合A到整体中 ab->Operation(); ab->SetImplementor(new ConcreteImplementorB());//组合B到整体中 ab->Operation(); system("pause"); }