桥模式

  桥模式:把抽象化与实现化解耦,使得二者可以独立变化。属于结构型模式,其通过提供抽象化和实现化间的桥接结构,来实现二者解耦。

实现:

  画出不同大小、颜色、线宽的图形。一般情况下,如果用为每种图形都提供各种不同颜色的设计思路来设计,当要增加图形种类或者颜色种类时,就要面临大量的工作量。以下是使用桥模式设计:

  1、定义桥接接口

1 class IDraw
2 {
3 public:
4     virtual void drawSharp(ISharp* sharp) = 0;
5     virtual ~IDraw() {};
6 };

  2、创建实现IDraw接口的实体桥接实现类

 1 class RedDraw : public IDraw
 2 {
 3     virtual void drawSharp(ISharp* sharp);
 4 };
 5 class GreeDraw : public IDraw
 6 {
 7     virtual void drawSharp(ISharp* sharp);
 8 };
 9 
10 void RedDraw::drawSharp(ISharp* sharp)
11 {
12     cout << "Red " << "weight = " << sharp->weight << endl;
13 }
14 
15 void GreeDraw::drawSharp(ISharp* sharp)
16 {
17     cout << "Gree " << "weight = " << sharp->weight << endl;
18 }

  3、创建使用IDraw接口的ISharp

1 class ISharp
2 {
3 protected:
4     IDraw* drawAPI;
5 public:
6     virtual void draw() = 0;
7     virtual ~ISharp() {};
8     int weight;
9 };

  4、创建使用ISharp的实体

class Circle : public ISharp
{
public:
    Circle(int x, int y, int radius, IDraw* drawAPI, int weight);
    virtual void draw();
protected:
    int x, y, radius;
};

Circle::Circle(int x, int y, int radius, IDraw* drawAPI, int weight)
{
    this->x = x;
    this->y = y;
    this->radius = radius;
    this->drawAPI = drawAPI;
    this->weight = weight;
}

void Circle::draw()
{
    cout << x << " " << y << " " << radius;
    drawAPI->drawSharp(this);
}

  5、使用ISharp和IDraw画出不同颜色,大小,线宽的圆

1 int main()
2 {
3     ISharp *redCircle = new Circle(0, 0, 10, new RedDraw(), 3);
4     ISharp* greeCircle = new Circle(1, 1, 43, new GreeDraw(), 5);
5 
6     redCircle->draw();
7     greeCircle->draw();
8 }

  使用桥模式,当我们要增加图形时只需要继承ISharp,要增加颜色就继承IDraw,要用的时候就将两者通过IDraw结合。

使用场景: 

  1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。

  2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。

  3、一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

posted @ 2019-10-27 20:34  qetuo[  阅读(416)  评论(0编辑  收藏  举报