--来自《设计模式:可复用面向对象软件的基础》
目的
将一个类的接口转换成客户希望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
类适配器
对象适配器
Class Shape
{
Public:
Shape();
Virtual void BoundingBox(Point& bottomLeft, Point& topRight)const;
Virtual Manipulator* CreateManipulator() const;
};
ClassTextView
{
Public:
TextView();
Void GetOrigin(Coord& x, Coord& y) const;
Void GetExtend(Coord& width, Coord& height) const;
Virtual bool IsEmpty() const;
};
ClassTextShape : public Shape, private TextView
{
Public:
TextShape();
Virtual void BoundingBox(Point& bottomLeft, Point& topRight)const;
Virtual bool IsEmpty() const;
Virtual Manipulator* CreateManipulator() const;
};
//对TextView接口进行转换使之匹配Shape
VoidTextShape::BoundingBox(Point& bottomLeft, Point& topRight) const
{
Coord bottom, left, width, height;
GetOrigin(bottom, left);
GetExtend(width, height);
bottomLeft = Point(bottom, left);
topRight = Point(bottom + height, left + width);
};
//对象适配器采用对象组合的方法将具有不同接口的类组合在一起。在该方法中,适配器TextShape维护一个指向TextView的指针
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*)
{
_text = t;//初始化
};
VoidTextShape::BoundingBox(Point& bottomLeft, Point& topRight) const
{
Coord bottom, left, width, height;
_text->GetOrigin(bottom, left);
_text->GetExtend(width, height);
bottomLeft = Point(bottom, left);
topRight = Point(bottom + height, left + width);
};