设计模式之桥接模式

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

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

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

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

UML图如下:


适用性:

----你不希望在抽象和它的实现部分之间有一个固定的绑定关系。

----类的抽象以及它的实现都应该可以通过生产子类的方法加以扩充。

----对一个抽象的实现部分的修改应对客户不产生影响,即客户的代码不必重新编译。

----(C++)你想对客户完全隐藏抽象的实现部分。

----你想在多个对象间共享实现,但同时要求客户并不知道这一点。


参与者:

Abstraction

----定义抽象类的接口

----维护一个指向Implementor类型对象的指针

RefinedAbstraction

----扩充由Abstraction定义的接口

Implementor

----定义实现类的接口,该接口不一定要与Abstraction的接口完全一致

ConcreteImplementor

----实现Implementor接口并定义它的具体实现


协作:

----Abstraction 将Client的请求转发给它的Implementor对象


效果:

----分离接口及其实现部分

----提高可扩充性

----实现细节对客户透明。


代码实现如下所示:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
using  namespace std;

class Implementor
{
public:
     virtual  void Operation() =  0;
};


class ConcreteImplementorA :  public Implementor
{
public:
     void Operation()
    {
        cout <<  "具体实现A的方法执行" << endl;
    }
};

class ConcreteImplementorB :  public Implementor
{
public:
     void Operation()
    {
        cout <<  "具体实现B的方法执行" << endl;
    }
};

class Abstraction
{
protected:
    Implementor *p_implementor;
public:
     void SetImplementor(Implementor *);
     virtual  void Operation();
};

void Abstraction::SetImplementor(Implementor *p_implementor)
{
    Abstraction::p_implementor = p_implementor;
}

void Abstraction::Operation()
{
    p_implementor->Operation();
}

class RefinedAbstraction :  public Abstraction
{
public:
     void Operation();
};

void RefinedAbstraction::Operation()
{
    p_implementor->Operation();
}

int main()
{
    Abstraction *a =  new RefinedAbstraction();
    a->SetImplementor( new ConcreteImplementorA());
    a->Operation();

    a->SetImplementor( new ConcreteImplementorB());
    a->Operation();
     return  0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值