概述
- 結構型模式
接下來七種設計模式歸爲結構型模式,旨在描述如何將類或對象按某種佈局組成更大的結構,其實現有一些類似,主要在功能性上有所區分。
在設計類的時候,如果某個類在多個維度特性上有變化,可以將這些特性抽離爲一個額外的繼承體系,實現將某些屬性與該類解耦,使得類的不同成員和功能得以分別變化,以達到在使用類時,用戶可以對其進行定製的目的,可以看作是一種變相的多態,與effective c++中提到的35條類似:
class DrawApi {
public:
virtual void Draw()=0;
};
class DrawRed :public DrawApi{
public:
void Draw() {
cout << "I am red";
}
};
class DrawBlue :public DrawApi {
public:
void Draw() {
cout << "I am Blue";
}
};
class Circle {
public:
Circle(int a,int b,drawApi* draw_api ):x(a),y(b),drawcircle_(draw_api){}
void draw() {
cout << x << ' ' << y << ' ';
draw_api_->Draw();
}
private:
int x;
int y;
drawApi *draw_api_;
};
int main() {
DrawApi draw_api = new DrawBlue();
circle a(3, 3, draw_api);
a.draw();
delete draw_api;
}
輸出:
3 3 I am Blue請按任意鍵繼續. . .