如何创建基于静态调度的工厂方法?

How to create a factory method based on static dispatch?

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

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!
}

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

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 特性。 对应的工厂和动态工厂非常相似;它只是构建返回枚举的特定变体而不是框。

你可以这样做:

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 方法不同,这不会 pre-decide 哪些东西可以具有工厂形状。)

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