设计模式之桥接模式

1、桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。

2、什么叫抽象与它的实现分离,这并不是说,让抽象类与其派生类分离,因为这没有任何意义。实现指的是抽象类和它的派生类用来实现自己的对象。

由于实现的方式多种,桥接模式的核心意图就是把这些实现独立出来,让它们各自地变化。这样就使得每种实现的变化不会影响其他实现,从而达到应对变化的目的。

实现系统可能要多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。

UML图如下:

 


3、C++代码实现如下:

[cpp] view plaincopy
 
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Implementor  
  5. {  
  6. public:  
  7.     virtual void Operation() = 0;  
  8. };  
  9.   
  10.   
  11. class ConcreteImplementorA : public Implementor  
  12. {  
  13. public:  
  14.     void Operation() {  
  15.         cout << "具体实现A的方法执行" << endl;  
  16.     }  
  17. };  
  18.   
  19. class ConcreteImplementorB : public Implementor  
  20. {  
  21. public:  
  22.     void Operation() {  
  23.         cout << "具体实现B的方法执行" << endl;  
  24.     }  
  25. };  
  26.   
  27. class Abstraction  
  28. {  
  29. protected:  
  30.     Implementor * p_implementor;  
  31. public:  
  32.     void SetImplementor(Implementor *);  
  33.     virtual void Operation();  
  34. };  
  35.   
  36. void Abstraction::SetImplementor(Implementor * p_implementor) {  
  37.     Abstraction::p_implementor = p_implementor;  
  38. }  
  39.   
  40. void Abstraction::Operation() {  
  41.     p_implementor->Operation();  
  42. }  
  43.   
  44. class RefinedAbstraction : public Abstraction  
  45. {  
  46. public:  
  47.     void Operation();  
  48. };  
  49.   
  50. void RefinedAbstraction::Operation() {  
  51.     p_implementor->Operation();  
  52. }  
  53.   
  54. int main()  
  55. {  
  56.     Abstraction * a = new RefinedAbstraction();  
  57.     a->SetImplementor(new ConcreteImplementorA());  
  58.     a->Operation();  
  59.   
  60.     a->SetImplementor(new ConcreteImplementorB());  
  61.     a->Operation();  
  62.     return 0;  
  63. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值