Rust 面向对象的相关设计

面向对象的基本概念

面向对象的三大特性:

  • 封装
  • 继承 (继承接口/实现)
  • 多态

Rust Trait 与面向对象的区别

设计哲学差异:

  • OOP 强调"接口定义契约,实现交给具体类"
  • Rust 的 trait 更倾向于"可组合的共享行为",既是接口也是混入(mixin)

混入(Mixin)是一种编程概念,用于在多个类之间共享代码和行为,而无需使用传统的继承机制。它的核心思想是将可复用的功能模块"混入"到不同的类中,从而避免单继承的限制,并提高代码的灵活性。

由于 Rust 的所有权系统有循环引用的限制, 在实现设计模式时, 可能会比传统面向对象语言的实现更复杂。

封装特性

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
struct Foo {
  // data
}

impl Foo {
  pub fn method_1() {
  }
  pub fn method_2() {
  }
}

继承接口/实现

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
trait Greet {
    // 方法签名(无默认实现,必须由实现者提供)
    fn say_hello(&self);                    // 继承接口

    // 带有默认实现的方法
    fn say_bye(&self) {                     // 继承接口与实现
        println!("Goodbye!");
    }
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn say_hello(&self) {
        println!("Hello, my name is {}!", self.name);
    }

    fn say_bye(&self) {
        println!("{} says: See you later!", self.name);
    }
}

struct Robot;

impl Greet for Robot {
    fn say_hello(&self) {
        println!("Beep boop, I'm a robot.");
    }

    // 不覆盖 `say_bye`,直接使用默认实现
}

fn main() {
    let person = Person {
        name: String::from("Alice"),
    };
    person.say_hello(); // 输出: Hello, my name is Alice!
    person.say_bye();   // 输出: Alice says: See you later!

    let robot = Robot;
    robot.say_hello(); // 输出: Beep boop, I'm a robot.
    robot.say_bye();   // 输出: Goodbye!(默认实现)
}

多态

提取并抽象共同的接口, 使用动态访问。

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
trait Greet {
    fn say_hello(&self);
    fn say_bye(&self) {
        println!("Goodbye!");
    }
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn say_hello(&self) {
        println!("Hello, my name is {}!", self.name);
    }
    fn say_bye(&self) {
        println!("{} says: See you later!", self.name);
    }
}

struct Robot;

impl Greet for Robot {
    fn say_hello(&self) {
        println!("Beep boop, I'm a robot.");
    }
}

fn main() {
    let person = Person {
        name: String::from("Alice"),
    };
    let robot = Robot;

    // 动态分发(Trait 对象)
    let greeters: Vec<&dyn Greet> = vec![&person, &robot];
    for g in greeters {
        g.say_hello();
        g.say_bye();
    }
}
0%