首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

我的設計模式之旅[3]:Strategy Pattern 多型傳遞 this 指標實作 (C++)

     編輯:關於C語言

本文承接前一篇,示範在不使用 Template 的情況下,如何利用多型與 *this 指標,讓 Grapher 將自身傳遞給策略物件,使策略能存取 Grapher 的公開介面(如 getText())。

介面設計

IShape 介面的 draw() 參數固定為 Grapher &,策略類別(Triangle、Circle、Square)繼承 IShape 並實作繪圖邏輯:

class IShape {
public:
    virtual void draw(Grapher &grapher) const = 0;
};

完整程式碼

程式碼截圖
#include <iostream>
#include <string>
using namespace std;

class Grapher;

class IShape {
public:
    virtual void draw(Grapher &grapher) const = 0;
};

class Grapher {
private:
    IShape *shape;
    string text;
public:
    Grapher() {}
    Grapher(IShape *shape, const char *text = "Hello Shape!!") 
        : shape(shape), text(string(text)) {}

    void drawShape() {
        this->shape->draw(*this);
    }
    void setShape(IShape *shape, const char* text = "Hello Shape!!") {
        this->text = text;
        this->shape = shape;
    }
    string getText() const { return this->text; }
};

class Triangle : public IShape {
public:
    void draw(Grapher &grapher) const {
        cout << "Draw " << grapher.getText() << " in Triangle" << endl;
    }
};

class Circle : public IShape {
public:
    void draw(Grapher &grapher) const {
        cout << "Draw " << grapher.getText() << " in Circle" << endl;
    }
};

class Square : public IShape {
public:
    void draw(Grapher &grapher) const {
        cout << grapher.getText() << " in Square" << endl;
    }
};

int main() {
    Grapher theGrapher(&Square());
    theGrapher.drawShape();
    theGrapher.setShape(&Circle(), "Hello C++!!");
    theGrapher.drawShape();
}

執行結果

Draw Hello Shape!! in Square
Draw Hello C++!! in Circle

小結

此版本透過多型機制,讓 Grapher 在執行期動態切換繪圖策略。雖然運作正常,但 IShape 仍強綁定 Grapher 型別,後續文章將引入 Template 解決此限制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved