設計模式之適配器(Adapter)---類對象結構型模式

       設計模式之適配器(Adapter)---類對象結構型模式

1.意圖

將一個類的接口轉換成客戶希望的另外一個接口。Adapter 模式使得原本由於接口不兼容而不能一起工作的那些類可以一起工作。

2.別名

包裝器Wrapper。

3.適用性

1)你想使用一個已經存在的類,而它的接口不符合你的需求。
2) 你想創建一個可以複用的類,該類可以與其他不相關的類或不可預見的類(即那些接口可能不一定兼容的類)協同工作。
3)(僅適用於對象Adapter)你想使用一些已經存在的子類,但是不可能對每一個都進行子類化以匹配它們的接口。對象適配器可以適配它的父類接口。

4.結構
1)類適配器使用多重繼承對一個接口與另一個接口進行匹配,如下圖A1


2)對象匹配器依賴於對象組合,如下圖A2示:

5.參與者

*Target
---定義Client 使用的與特定領域相關的接口。
*Client
---與符合Target接口的對象協同。
*Adaptee
---定義一個已存在的接口,這個接口需要適配。
*Adapter
---對Adaptee的接口與Target接口進行匹配。

6.協作

Client在Adapter實例上調用一些操作。接着適配調用Adaptee的操作實現這個請求。

7.代碼示例:

/**************************************************************************
*
*
* 對應關係:TextView---Adaptee
* TextShape---Adapter
*

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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章