-3

我想学习设计模式使用 rust 语言。从这段代码中它可以正常工作,但它使用动态调度。如何更改代码以使用静态调度?谢谢!

trait Shape {
    fn draw(&self);
}

enum ShapeType {
    Rectangle,
    Circle,
}

struct Rectangle {}

impl Shape for Rectangle {
    fn draw(&self) {
        println!("draw a rectangle!");
    }
}

struct Circle {}

impl Shape for Circle {
    fn draw(&self) {
        println!("draw a circle!");
    }
}

struct ShapeFactory;
impl ShapeFactory {
    fn new_shape(s: &ShapeType) -> Box<dyn Shape> {
        match s {
            ShapeType::Circle => Box::new(Circle {}),
            ShapeType::Rectangle => Box::new(Rectangle {}),
        }
    }
}

fn main() {
    let shape = ShapeFactory::new_shape(&ShapeType::Circle);
    shape.draw(); // output: draw a circle!

    let shape = ShapeFactory::new_shape(&ShapeType::Rectangle);
    shape.draw(); // output: draw a rectangle!
}
4

2 回答 2

1

你可以这样做:

trait ShapeFactory {
    type Product: Shape;
    fn new_shape() -> Self::Product;
}

struct CircleFactory;
impl ShapeFactory for CircleFactory {
    type Product = Circle;
    fn new_shape() -> Circle {
        Circle {}
    }
}

// separate method, to demonstrate the factory part a bit better
fn draw_new_shape<F: ShapeFactory>() {
    let shape = F::new_shape();
    shape.draw();
}

fn main() {
    draw_new_shape::<CircleFactory>();
}

(与- 方法不同enum,这不会预先决定哪些东西可以具有工厂形状。)

你应该做这样的事情吗?很可能没有。我高度怀疑工厂作为 Rust 中的“设计模式”的有效性。

于 2022-02-21T15:02:43.163 回答
0

在提供的示例中,我将添加

enum StaticShape {
    Rectangle(Rectangle),
    Circle(Circle),
}

impl Shape for StaticShape {
    fn draw(&self) {
        match self {
            StaticShape::Rectangle(sh) => sh.draw(),
            StaticShape::Circle(sh) => sh.draw(),
        }
    }
}

struct StaticShapeFactory;
impl StaticShapeFactory {
    fn new_shape(s: &ShapeType) -> StaticShape {
        match s {
            ShapeType::Rectangle => StaticShape::Rectangle(Rectangle {}),
            ShapeType::Circle => StaticShape::Circle(Circle {}),
        }
    }
}

并在main()函数中

    let shape = StaticShapeFactory::new_shape(&ShapeType::Circle);
    shape.draw(); // output: draw a circle!

    let shape = StaticShapeFactory::new_shape(&ShapeType::Rectangle);
    shape.draw(); // output: draw a rectangle!

StaticShape枚举枚举可以处理的每个可能的特定形状。为了表现得像一个形状,它Shape通过简单地将调用转发到特定的形状类型来实现特征。对应的工厂与动态工厂非常相似;它只是构建返回的枚举的特定变体而不是一个框。

于 2022-02-21T14:51:50.310 回答