利用 Template 將類別適配器的被適配類別參數化,單一 DrawAdapter<T> 替代多個具體適配器類別。
template<typename T>
class DrawAdapter : public IDrawStrategy, private T {
public:
virtual void draw() const;
};
template<typename T>
void DrawAdapter<T>::draw() const { paint(); }
int main() {
Grapher grapher(new DrawAdapter<Triangle>());
grapher.drawShape();
grapher.setShape(new DrawAdapter<Circle>());
grapher.drawShape();
grapher.setShape(new DrawAdapter<Square>());
grapher.drawShape();
}
template<typename T>
ref class DrawAdapter : public IDrawStrategy, public T {
public:
virtual void draw();
};
template<typename T>
void DrawAdapter<T>::draw() { paint(); }
Draw Triangle
Draw Circle
Draw Square
Template 版本保留類別適配器「繼承被適配類別」的優勢(易於 override),同時消除類別爆炸,客戶端可動態決定具體型別,兼具靜態型別安全與執行期彈性。