设计过程
- 抽象出图形和平台的接口:
- 创建一个绘制平台的抽象接口,每个具体平台(如Windows、Linux)实现该接口。
- 创建一个图形的抽象类,包含指向绘制平台接口的指针,并定义绘制图形的抽象方法。每个具体图形(如圆形、矩形)继承该抽象类,并实现绘制方法,调用平台接口的绘制操作。
核心代码(以C++为例)
// 绘制平台接口
class DrawingPlatform {
public:
virtual void drawCircle(float x, float y, float radius) = 0;
virtual void drawRectangle(float x1, float y1, float x2, float y2) = 0;
virtual ~DrawingPlatform() = default;
};
// Windows绘制平台实现
class WindowsDrawingPlatform : public DrawingPlatform {
public:
void drawCircle(float x, float y, float radius) override {
// 实际的Windows绘制圆形逻辑
std::cout << "Windows: Drawing circle at (" << x << ", " << y << ") with radius " << radius << std::endl;
}
void drawRectangle(float x1, float y1, float x2, float y2) override {
// 实际的Windows绘制矩形逻辑
std::cout << "Windows: Drawing rectangle from (" << x1 << ", " << y1 << ") to (" << x2 << ", " << y2 << ")" << std::endl;
}
};
// Linux绘制平台实现
class LinuxDrawingPlatform : public DrawingPlatform {
public:
void drawCircle(float x, float y, float radius) override {
// 实际的Linux绘制圆形逻辑
std::cout << "Linux: Drawing circle at (" << x << ", " << y << ") with radius " << radius << std::endl;
}
void drawRectangle(float x1, float y1, float x2, float y2) override {
// 实际的Linux绘制矩形逻辑
std::cout << "Linux: Drawing rectangle from (" << x1 << ", " << y1 << ") to (" << x2 << ", " << y2 << ")" << std::endl;
}
};
// 图形抽象类
class Shape {
protected:
DrawingPlatform* platform;
public:
Shape(DrawingPlatform* platform) : platform(platform) {}
virtual void draw() = 0;
virtual ~Shape() = default;
};
// 圆形类
class Circle : public Shape {
private:
float x;
float y;
float radius;
public:
Circle(DrawingPlatform* platform, float x, float y, float radius) : Shape(platform), x(x), y(y), radius(radius) {}
void draw() override {
platform->drawCircle(x, y, radius);
}
};
// 矩形类
class Rectangle : public Shape {
private:
float x1;
float y1;
float x2;
float y2;
public:
Rectangle(DrawingPlatform* platform, float x1, float y1, float x2, float y2) : Shape(platform), x1(x1), y1(y1), x2(x2), y2(y2) {}
void draw() override {
platform->drawRectangle(x1, y1, x2, y2);
}
};
使用示例
int main() {
DrawingPlatform* windowsPlatform = new WindowsDrawingPlatform();
Shape* circleOnWindows = new Circle(windowsPlatform, 100, 100, 50);
circleOnWindows->draw();
DrawingPlatform* linuxPlatform = new LinuxDrawingPlatform();
Shape* rectangleOnLinux = new Rectangle(linuxPlatform, 50, 50, 150, 150);
rectangleOnLinux->draw();
delete circleOnWindows;
delete rectangleOnLinux;
delete windowsPlatform;
delete linuxPlatform;
return 0;
}