您的位置:首页 > 其它

设计模式:adapter适配器

2016-08-05 15:38 267 查看
1.动机

    client想要用adaptee的功能,但是client的调用的接口跟adaptee提供的接口不匹配,这个时候需要adapter做适配。

2.实现方式

2.1 类适配

adapter2公共继承Target,私有继承Adaptee2,并将target的request()指向Adaptee2的specificRequest().

优点:

由于Adapter2是Adaptee2的子类,可以置换或丰富Adaptee2的方法,灵活性更强;

缺点:

在java等语言中不支持多重继承。



2.2 对象适配

adapter继承Target,并实例化Adaptee对象

优点:

可以实例化多个adaptee对象,一个adapter可以Adaptee类和它的子类都适配到Target接口;

缺点:

不能灵活修改功能



3.实例

/*
*/
#include "Geom.H"
// Compilation Instructions
// With ClassAdapter defined and not defined
#define ClassAdapter 0
/*
*/
class Manipulator;
/*
*/
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;
};
/*
*/
#ifdef ClassAdapter
/*
*/
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 Manipulator {
};
class TextManipulator : public Manipulator {
public:
TextManipulator(const TextShape*);
};
/*
*/
Manipulator* TextShape::CreateManipulator () const {
return new TextManipulator(this);
}
/*
*/
#endif
#ifndef ClassAdapter
class TextView;
class Manipulator {
};
class TextManipulator : public Manipulator {
public:
TextManipulator();
};
/*
*/
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();
}
/*
*/
Manipulator* TextShape::CreateManipulator () const {
return new TextManipulator(this);
}
/*
*/
#endif
/*
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式