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

我的設計模式之旅[6]:Adapter Pattern 物件適配器 ISO C++ 實作

     編輯:關於C語言

ISO C++ 版物件適配器,使用指標與虛擬函數實作多型。DrawAdapter 持有 IPaint*,draw() 轉呼叫 _adaptee->paint()。

完整程式碼

#include <iostream>
using namespace std;

class IDrawStrategy { public: virtual void draw() const = 0; };

class Grapher {
    IDrawStrategy* _drawStrategy;
public:
    Grapher(IDrawStrategy* ds = 0) : _drawStrategy(ds) {}
    void drawShape() const { if (_drawStrategy) _drawStrategy->draw(); }
    void setShape(IDrawStrategy* ds) { _drawStrategy = ds; }
};

class IPaint { public: virtual void paint() const = 0; };

class Triangle : public IPaint { public: void paint() const { cout << "Draw Triangle" << endl; } };
class Circle : public IPaint { public: void paint() const { cout << "Draw Circle" << endl; } };
class Square : public IPaint { public: void paint() const { cout << "Draw Square" << endl; } };

class DrawAdapter : public IDrawStrategy {
    IPaint* _adaptee;
public:
    DrawAdapter(IPaint* adaptee = 0) : _adaptee(adaptee) {}
    virtual void draw() const { _adaptee->paint(); }
};

int main() {
    Grapher grapher(new DrawAdapter(new Triangle()));
    grapher.drawShape();
    grapher.setShape(new DrawAdapter(new Circle()));
    grapher.drawShape();
    grapher.setShape(new DrawAdapter(new Square()));
    grapher.drawShape();
}

注意:範例為簡化未處理記憶體釋放,實務上應使用智慧指標管理生命週期。

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