程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 我的Design Pattern之旅[6]:Adapter Pattern(OO)(11)

我的Design Pattern之旅[6]:Adapter Pattern(OO)(11)

編輯:關於C語言

Object Adapter

ISO C++

/**//*
(C) OOMusou 2007 http://oomusou.cnblogs.com

Filename  : DP_AdpaterPattern_Strategy_Object.cpp
Compiler  : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
Description : Demo how to use Strategy Pattern with Adapter Pattern (Object)
Release   : 07/11/2007 1.0
*/
#include <iOStream>
using namespace std;

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

class Grapher {
public:
 Grapher(IDrawStrategy* drawStrategy = 0) : _drawStrategy(drawStrategy) {}

public:
 void drawShape() const;
 void setShape(IDrawStrategy* drawStrategy);

protected:
 IDrawStrategy* _drawStrategy;
};

void Grapher::drawShape() const {
 if (_drawStrategy)
   _drawStrategy->draw();
}

void Grapher::setShape(IDrawStrategy* drawStrategy) {
 _drawStrategy = drawStrategy;
}

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

class Triangle : public IPaint {
public:
 void paint() const;
};

void Triangle::paint() const {
 cout << "Draw Triangle" << endl;
}

class Circle : public IPaint {
public:
 void paint() const;
};

void Circle::paint() const {
 cout << "Draw Circle" << endl;
}

class Square : public IPaint {
public:
 void paint() const;
};

void Square::paint() const {
 cout << "Draw Square" << endl;
}

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

protected:
 IPaint* _adaptee;
};

void DrawAdapter::draw() const {
 _adaptee->paint();
}

int main() {
 Grapher grapher(&DrawAdapter(&Triangle()));
 grapher.drawShape();

 grapher.setShape(&DrawAdapter(&Circle()));
 grapher.drawShape();

 grapher.setShape(&DrawAdapter(&Square()));
 grapher.drawShape();
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved