The Bridge Pattern C++实现

  Summary: One Rule, One place

A very important rule to follow is there is only one place to have where you implement a rule.

当需要改变一个规则的时候,只有在一个地方进行修改,才能尽可能减少出错的可能性。

当抽象类和它的实现都有可能变化的时候,我们将这实现分离出来,即封装实现的具体内容来避免随着修改的进行而出现类爆炸的情况,并且能够实现低耦合和高内聚。

这里还有设计最基本的规则就是:

1、找出哪些是变化的并封装这些变化

2、多用组合而少用继承

3     对接口进行设计


对于本章中的例子来说,开始的设计如下:

缺点:当增加一个Shape的时候,都需要修改,需要重新增加一个子类,并且还都要实现如何来画这个Shape的代码。当增加一个DP3的时候,需要对所用现有的Shape都要增加关于V3XXX的实现,而且随着增加,会出现类爆炸式的增长。

运用Bridge模式,首先找出哪些是有可能变化的,在这里是ShapeDraw的实现方式,首先抽象出两个类:


第二步,确定这些变化

第三步, 确定谁应该用谁

第四步 扩展这些类



下面是该模式的C++的实现
#include  < iostream.h >
#include 
< stdio.h >

class  DP1
{
public:
    
static void Draw_a_Line()
    
{
       cout
<<"DP1 is drawing line"<<endl;
    }
;
    
static void Draw_a_Circle()
    
{
           cout
<<"DP1 is drawing circle"<<endl;
    }
;
}
;
class  DP2
{
public:
    
static void DrawLine()
    
{
       cout
<<"DP2 is drawing line"<<endl;
    }
;
    
static void DrawCircle()
    
{
           cout
<<"DP2 is drawing circle"<<endl;
    }
;
}
;
class  Drawing {
public:
    
virtual void DrawLine()=0;
    
virtual void DrawCircle()=0;

}
;

class  Shape {    
public:
    Shape(Drawing 
*_dp){dp=_dp;};
public:
    
virtual void Draw()=0;
private:
    Drawing
* dp;
protected:
    
void DrawLine(){dp->DrawLine();};
    
void DrawCircle(){dp->DrawCircle();};    
}
;

class  Rect: public  Shape
{
public:
    Rect(Drawing
* _dp);
    
public:
    
void Draw(){DrawLine();};


}
;
Rect::Rect(Drawing
*  _dp):Shape(_dp)
{    
}

class  Circle: public  Shape
{

public:
    Circle(Drawing
* _dp);
    
void Draw(){DrawCircle();};

}
;
Circle::Circle(Drawing
*  _dp):Shape(_dp)
{

}

class  V1Drawing: public  Drawing {
private:
    DP1 dp;
public:
    
void DrawLine(){
        dp.Draw_a_Line();
    }
;
    
void DrawCircle(){
     dp.Draw_a_Circle();
    
    }
;

}
;
class  V2Drawing: public  Drawing {
private:
    DP2 dp;
public:
    
void DrawLine(){
        dp.DrawLine();
    }
;
    
void DrawCircle(){
    dp.DrawCircle();
    }
;

}
;

void  main()
{
    Shape
* s1,*s2;
    Drawing
* d1,*d2;
    d1
=new V1Drawing();
    d2
=new V2Drawing();
    s1
=new Rect(d1);
    
    s1
->Draw();
    delete s1;
    s1
=new Rect(d2);
    s1
->Draw();
    s2
=new Circle(d1);
    s2
->Draw();    
    delete s2;
    s2
=new Circle(d2);
    s2
->Draw();
    getchar();
    delete s1;
    delete s2;
    delete d1;
    delete d2;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值