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

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

編輯:關於C語言

C++/CLI

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

Filename  : DP_AdpaterPattern_Strategy_Object.cpp
Compiler  : Visual C++ 8.0 / C++/CLI
Description : Demo how to use Strategy Pattern with Adpater Pattern (Object)
Release   : 07/12/2007 1.0
*/
#include "stdafx.h"
using namespace System;

interface class IDrawStrategy {
 void draw();
};

ref class Grapher {
public:
 Grapher() : _drawStrategy(nullptr) {}
 Grapher(IDrawStrategy^ drawStrategy) : _drawStrategy(drawStrategy) {}

public:
 void drawShape();
 void setShape(IDrawStrategy^ drawStrategy);

protected:
 IDrawStrategy^ _drawStrategy;
};

void Grapher::drawShape() {
 if (_drawStrategy != nullptr)
   _drawStrategy->draw();
}

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

interface class IPaint {
 void paint();
};

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

void Triangle::paint() {
 Console::WriteLine("Draw Triangle");
}

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

void Circle::paint() {
 Console::WriteLine("Draw Circle");
}

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

void Square::paint() {
 Console::WriteLine("Draw Square");
}

ref class DrawAdapter : public IDrawStrategy {
public:
 DrawAdapter() : _adaptee(nullptr) {}
 DrawAdapter(IPaint^ adaptee) : _adaptee(adaptee) {}
 virtual void draw();

protected:
 IPaint^ _adaptee;
};

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

int main() {
 Grapher^ grapher = gcnew Grapher(gcnew DrawAdapter(gcnew Triangle));
 grapher->drawShape();

 grapher->setShape(gcnew DrawAdapter(gcnew Circle));
 grapher->drawShape();

 grapher->setShape(gcnew DrawAdapter(gcnew Square));
 grapher->drawShape();
}

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