面试题答案
一键面试设计思路
- 基础特征
Graphic
:定义所有图形共有的渲染行为,作为图形类型的基础抽象。 - 变换特征
Translateable
、Rotatable
、Scalable
:分别定义平移、旋转、缩放的操作方法,使得实现这些特征的结构体能够进行相应变换。 - 结构体层次:创建具体图形结构体(如
Point
、Line
、Polygon
),这些结构体实现Graphic
特征,并且根据需要实现变换特征。通过这种方式,不同图形可以灵活组合不同变换特征。在渲染前,通过调用变换特征的方法应用变换。
核心代码示例(以 Rust 语言为例)
// 基础图形特征
trait Graphic {
fn render(&self);
}
// 平移特征
trait Translateable {
fn translate(&mut self, x: f32, y: f32);
}
// 旋转特征
trait Rotatable {
fn rotate(&mut self, angle: f32);
}
// 缩放特征
trait Scalable {
fn scale(&mut self, factor: f32);
}
// 点结构体
struct Point {
x: f32,
y: f32,
}
impl Graphic for Point {
fn render(&self) {
println!("Rendering point at ({}, {})", self.x, self.y);
}
}
impl Translateable for Point {
fn translate(&mut self, x: f32, y: f32) {
self.x += x;
self.y += y;
}
}
// 线结构体
struct Line {
start: Point,
end: Point,
}
impl Graphic for Line {
fn render(&self) {
println!("Rendering line from ({}, {}) to ({}, {})", self.start.x, self.start.y, self.end.x, self.end.y);
}
}
impl Translateable for Line {
fn translate(&mut self, x: f32, y: f32) {
self.start.translate(x, y);
self.end.translate(x, y);
}
}
// 多边形结构体
struct Polygon {
points: Vec<Point>,
}
impl Graphic for Polygon {
fn render(&self) {
println!("Rendering polygon with points:");
for point in &self.points {
println!("({}, {})", point.x, point.y);
}
}
}
impl Translateable for Polygon {
fn translate(&mut self, x: f32, y: f32) {
for point in &mut self.points {
point.translate(x, y);
}
}
}
fn main() {
let mut point = Point { x: 0.0, y: 0.0 };
point.translate(1.0, 2.0);
point.render();
let mut line = Line {
start: Point { x: 0.0, y: 0.0 },
end: Point { x: 1.0, y: 1.0 },
};
line.translate(1.0, 1.0);
line.render();
let mut polygon = Polygon {
points: vec![
Point { x: 0.0, y: 0.0 },
Point { x: 1.0, y: 0.0 },
Point { x: 0.5, y: 1.0 },
],
};
polygon.translate(1.0, 1.0);
polygon.render();
}
上述代码首先定义了基础图形特征 Graphic
以及平移、旋转、缩放的变换特征。接着实现了 Point
、Line
、Polygon
三种图形结构体,并为它们实现了 Graphic
特征和 Translateable
特征。在 main
函数中展示了如何对这些图形进行平移操作并渲染。如果需要实现旋转和缩放,按照类似的方式为相应结构体实现 Rotatable
和 Scalable
特征即可。