Using the visitor pattern
The visitor design pattern is a common pattern used in object-oriented languages. A visitor stores an algorithm that operates over a collection of objects of different types. It allows multiple different algorithms to be written over the same data without having to modify the code of the data's classes (For a more detailed description, see https://en.wikipedia.org/wiki/Visitor_pattern).
Let's implement a visitor to calculate the area of different geometric objects, such as squares and circles.
// see code in Chapter 6/code/visitor_pattern.rs
// structs:
struct Point {
x: f64,
y: f64
}
struct Circle {
center: Point,
radius: f64,
}
struct Square {
lowerLeftCorner: Point,
side: f64,
}
// traits:
trait ShapeVisitor {
fn visit_circle(&mut self, c: &Circle);
fn visit_square(&mut self, r: &Square);
}
trait Shape {
fn accept<V: ShapeVisitor>(&self, sv: &mut V);
}
impl Shape for...