设计模式学习笔记(七)——Adapter适配器

六、Adapter(适配器)

情景举例:

解决类之间由于接口不匹配而不能复用的情况。

代码示例:

/* 目标类
     
     
*/
class Shape {
public:
    Shape();
    virtual void BoundingBox(
        Point& bottomLeft, Point& topRight
    ) const;
    virtual Manipulator* CreateManipulator() const;
};
/* 待匹配类
     
     
*/
class TextView {
public:
    TextView();
    void GetOrigin(Coord& x, Coord& y) const;
    void GetExtent(Coord& width, Coord& height) const;
    virtual bool IsEmpty() const;
};
/* 类适配器:公有继承目标类,私有继承待匹配类
*/
class TextShape : public Shape, private TextView {
public:
    TextShape();

  
  
   
    
  
  
    virtual void BoundingBox(
        Point& bottomLeft, Point& topRight
    ) const;
    virtual bool IsEmpty() const;
    virtual Manipulator* CreateManipulator() const;
};
/*
*/
void TextShape::BoundingBox (
    Point& bottomLeft, Point& topRight
) const {
    Coord bottom, left, width, height;

  
  
   
    
  
  
    GetOrigin(bottom, left);
    GetExtent(width, height);
/*
*/
    bottomLeft = Point(bottom, left);
    topRight = Point(bottom + height, left + width);
}
/* 常见的直接转发请求的用法
*/
bool TextShape::IsEmpty () const {
    return TextView::IsEmpty();
}
/* 对象适配器:公有继承目标类,以一个待匹配类的实例作为私有成员变量
*/
class TextShape : public Shape {
public:
    TextShape(TextView*);

  
  
   
    
  
  
    virtual void BoundingBox(
        Point& bottomLeft, Point& topRight
    ) const;
    virtual bool IsEmpty() const;
    virtual Manipulator* CreateManipulator() const;
private:
    TextView* _text;
};
/*
*/
TextShape::TextShape (TextView* t) {
    _text = t;
}
/*
*/
void TextShape::BoundingBox (
    Point& bottomLeft, Point& topRight
) const {
    Coord bottom, left, width, height;

  
  
   
    
  
  
    _text->GetOrigin(bottom, left);
    _text->GetExtent(width, height);

  
  
   
    
  
  
    bottomLeft = Point(bottom, left);
    topRight = Point(bottom + height, left + width);
}
/*
*/
bool TextShape::IsEmpty () const {
    return _text->IsEmpty();
}

个人理解:

适配器模式只是简单改变类的接口的模式,主要分析下类适配器与对象适配器的区别。

类适配器由于私有继承了待匹配类,则可以重定义其部分操作。而对象适配器不能。对象适配器可以应用在需要匹配某一父类和其全部子类的情况下,而类适配器则不能胜任。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值