Rust编程语言入门之Rust的面向对象编程特性

Rust 的面向对象编程特性

一、面向对象语言的特性

Rust是面向对象编程语言吗?

  • Rust 受到多种编程范式的影响,包括面向对象
  • 面向对象通常包含以下特性:命名对象、封装、继承

对象包含数据和行为

  • “设计模式四人帮”在《设计模型》中给面向对象的定义:
    • 面向对象的程序由对象组成
    • 对象包装了数据和操作这些数据的过程,这些过程通常被称作方法或操作
  • 基于此定义:Rust是面向对象的
    • struct、enum 包含数据
    • impl 块为之提供了方法
    • 但带有方法的 struct、enum 并没有被称为对象

封装

  • 封装:调用对象外部的代码无法直接访问对象内部的实现细节,唯一可以与对象进行交互的方法就是通过它公开的 API
  • Rust:pub 关键字
pub struct AveragedCollection {
  list: Vec<i32>,
  average: f64,
}

impl AveragedCollection {
  pub fn add(&mut self, value: i32) {
    self.list.push(value);
    self.update_average();
  }
  
  pub fn remove(&mut self) -> Option<i32> {
    let result = self.list.pop();
    match result {
      Some(value) => {
        self.update_average();
        Some(value)
      },
      None => None,
    }
  }
  
  pub fn average(&self) -> f64 {
    self.average
  }
  
  fn update_average(&mut self) {
    let total: i32 = self.list.iter().sum();
    self.average = total as f64 / self.list.len() as f64;
  }
}

继承

  • 继承:使对象可以沿用另外一个对象的数据和行为,且无需重复定义相关代码
  • Rust:没有继承
  • 使用继承的原因:
    • 代码复用
      • Rust:默认 trait 方法来进行代码共享
    • 多态
      • Rust:泛型和 trait 约束(限定参数化多态 bounded parametric)
  • 很多新语言都不使用继承作为内置的程序设计方案了。

二、使用 trait 对象来存储不同类型的值

有这样一个需求

  • 创建一个 GUI 工具:
    • 它会遍历某个元素的列表,依次调用元素的 draw 方法进行绘制
    • 例如:Button、TextField 等元素
  • 在面向对象语言里:
    • 定义一个 Component 父类,里面定义了 draw 方法
    • 定义 Button、TextField 等类,继承与 Component 类

为共有行为定义一个 trait

  • Rust 避免将 struct 或 enum 称为对象,因为他们与 impl 块是分开的
  • trait 对象有些类似于其它语言中的对象:
    • 它们某种程度上组合了数据与行为
  • trait 对象与传统对象不同的地方:
    • 无法为 trait 对象添加数据
  • trait 对象被专门用于抽象某些共有行为,它没其它语言中的对象那么通用

Trait 动态 lib.rs 文件

pub trait Draw {
  fn draw(&self);
}

pub struct Screen {
  pub components: Vec<Boc<dyn Draw>>,
}

impl Screen {
  pub fn run(&self) {
    for component in self.components.iter() {
      component.draw();
    }
  }
}

pub struct Button {
  pub width: u32,
  pub height: u32,
  pub label: String,
}

impl Draw for Button {
  fn draw(&self) {
    // 绘制一个按钮
  }
}

泛型的实现 一次只能实现一个类型

pub struct Screen<T: Draw> {
  pub components: Vec<T>,
}

impl<T> Screen<T>
where
	T: Draw,
{
  pub fn run(&self) {
    for component in self.components.iter() {
      component.draw()
    }
  }
}

main.rs 文件

use oo::Draw;
use oo::{Button, Screen};

struct SelectBox {
  width: u32,
  height: u32,
  options: Vec<String>,
}

impl Draw for SelectBox {
  fn draw(&self) {
    // 绘制一个选择框
  }
}

fn main() {
  let screen = Screen {
    components: vec![
      Box::new(SelectBox {
        width: 75,
        height: 10,
        options: vec![
          String::from("Yes"),
          String::from("Maybe"),
          String::from("No"),
        ],
      }),
      Box::new(Button {
        width: 50,
        height: 10,
        label: String::from("OK"),
      }),
    ],
  };
  
  screen.run();
}

Trait 对象执行的是动态派发

  • 将 trait 约束作用于泛型时,Rust编译器会执行单态化:
    • 编译器会为我们用来替换泛型参数的每一个具体类型生成对应函数和方法的非泛型实现。
  • 通过单态化生成的代码会执行静态派发(static dispatch),在编译过程中确定调用的具体方法
  • 动态派发(dynamic dispatch):
    • 无法在编译过程中确定你调用的究竟是哪一种方法
    • 编译器会产生额外的代码以便在运行时找出希望调用的方法
  • 使用 trait 对象,会执行动态派发:
    • 产生运行时开销
    • 阻止编译器内联方法代码,使得部分优化操作无法进行

Trait 对象必须保证对象安全

  • 只能把满足对象安全(object-safe)的 trait 转化为 trait 对象
  • Rust采用一系列规则来判定某个对象是否安全,只需记住两条:
    • 方法的返回类型不是 Self
    • 方法中不包含任何泛型类型参数

lib.rs 文件

pub trait Draw {
  fn draw(&self);
}

pub trait Clone {
  fn clone(&self) -> Self;
}

pub struct Screen {
  pub components: Vec<Box<dyn Clone>>, // 报错
}

三、实现面向对象的设计模式

状态模式

  • 状态模式(state pattern)是一种面向对象设计模式:
    • 一个值拥有的内部状态由数个状态对象(state object)表达而成,而值的行为则随着内部状态的改变而改变
  • 使用状态模式意味着:
    • 业务需求变化时,不需要修改持有状态的值的代码,或者使用这个值的代码
    • 只需要更新状态对象内部的代码,以便改变其规则,或者增加一些新的状态对象

例子:发布博客的工作流程 main.rs

use blog::Post;

fn main() {
  let mut post = Post::new();
  
  post.add_text("I ate a salad for lunch today");
  assert_eq!("", post.content());
  
  post.request_review();
  assert_eq!("", post.content());
  
  post.approve();
  assert_eq!("I ate a salad for lunch today", post.content());
}

lib.rs 文件

pub struct Post {
  state: Option<Box<dyn State>>,
  content: String,
}

impl Post {
  pub fn new() -> Post {
    Post {
      state: Some(Box::new(Draft {})),
      content: String::new(),
    }
  }
  pub fn add_text(&mut self, text: &str) {
    self.content.push_str(text);
  }
  
  pub fn content(&self) -> &str {
    ""
  }
  
  pub fn request_review(&mut self) {
    if let Some(s) = self.state.take() {
      self.state = Some(s.request_review())
    }
  }
  
  pub fn approve(&mut self) {
    if let Some(s) = self.state.take() {
      self.state = Some(s.approve())
    }
  }
}

trait State {
  fn request_review(self: Box<Self>) -> Box<dyn State>;
  fn approve(self: Box<Self>) -> Box<dyn State>;
}

struct Draft {}

impl State for Draft {
  fn request_review(self: Box<Self>) -> Box<dyn State> {
    Box::new(PendingReview {})
  }
  
  fn approve(self: Box<Self>) -> Box<dyn State> {
    self
  }
}

struct PendingReview {}

impl State for PendingRevew {
  fn request_review(self: Box<Self>) -> Box<dyn State> {
    self
  }
  
  fn approve(self: Box<Self>) -> Box<dyn State> {
    Box::new(Published {})
  }
}

struct Published {}

impl State for Published {
  fn request_review(self: Box<Self>) -> Box<dyn State> {
    self
  }
  
  fn approve(self: Box<Self>) -> Box<dyn State> {
    self
  }
}

修改之后:

pub struct Post {
  state: Option<Box<dyn State>>,
  content: String,
}

impl Post {
  pub fn new() -> Post {
    Post {
      state: Some(Box::new(Draft {})),
      content: String::new(),
    }
  }
  pub fn add_text(&mut self, text: &str) {
    self.content.push_str(text);
  }
  
  pub fn content(&self) -> &str {
    self.state.as_ref().unwrap().content(&self)
  }
  
  pub fn request_review(&mut self) {
    if let Some(s) = self.state.take() {
      self.state = Some(s.request_review())
    }
  }
  
  pub fn approve(&mut self) {
    if let Some(s) = self.state.take() {
      self.state = Some(s.approve())
    }
  }
}

trait State {
  fn request_review(self: Box<Self>) -> Box<dyn State>;
  fn approve(self: Box<Self>) -> Box<dyn State>;
  fn content<'a>(&self, post: &'a Post) -> &'a str {
    ""
  }
}

struct Draft {}

impl State for Draft {
  fn request_review(self: Box<Self>) -> Box<dyn State> {
    Box::new(PendingReview {})
  }
  
  fn approve(self: Box<Self>) -> Box<dyn State> {
    self
  }
}

struct PendingReview {}

impl State for PendingRevew {
  fn request_review(self: Box<Self>) -> Box<dyn State> {
    self
  }
  
  fn approve(self: Box<Self>) -> Box<dyn State> {
    Box::new(Published {})
  }
}

struct Published {}

impl State for Published {
  fn request_review(self: Box<Self>) -> Box<dyn State> {
    self
  }
  
  fn approve(self: Box<Self>) -> Box<dyn State> {
    self
  }
  
  fn content<'a>(&self, post: &'a Post) -> &'a str {
    &post.content
  }
}

状态模式的取舍权衡

  • 缺点:
    • 某些状态之间是相互耦合的
    • 需要重复实现一些逻辑代码

将状态和行为编码为类型

  • 将状态编码为不同的类型:
    • Rust 类型检查系统会通过编译时错误来阻止用户使用无效的状态

lib.rs 代码:

pub struct Post {
  content: String,
}

pub struct DraftPost {
  content: String,
}

impl Post {
  pub fn new() -> DraftPost {
    DraftPost {
      content: String::new(),
    }
  }
  pub fn content(&self) -> &str {
    &self.content
  }
}

impl DraftPost {
  pub fn add_text(&mut self, text: &str) {
    self.content.push_str(text);
  }
  pub fn request_review(self) -> PendingReviewPost {
    PendingReviewPost {
      content: self.content,
    }
  }
}

pub struct PendingReviewPost {
  content: String,
}

impl PendingReviewPost {
  pub fn approve(self) -> Post {
    Post {
      content: self.content,
    }
  }
}

main.rs 代码:

use blog::Post;

fn main() {
  let mut post = Post::new();
  
  post.add_text("I ate a salad for lunch today");
  
  let post = post.request_review();
  
  let post = post.approve();
  
  assert_eq!("I ate a salad for lunch today", post.content());
}

总结

  • Rust 不仅能够实现面向对象的设计模式,还可以支持更多的模式
  • 例如:将状态和行为编码为类型
  • 面向对象的经典模式并不总是 Rust 编程实践中的最佳选择,因为 Rust具有所有权等其它面向对象语言没有的特性!
posted @ 2023-04-20 22:04  寻月隐君  阅读(184)  评论(0编辑  收藏  举报