目录Rust的面向对象特性面向对象特点trait对象面向对象设计模式实现Rust的面向对象特性Rust的面向对象特性Rust的面向对象特点Rust并没有传统意义上的面向对象编程(OOP)的概念,但它通过组合和一些高级特性(如trait和泛型)实现了类似OOP
Rust 的面向对象特点
Rust 并没有传统意义上的面向对象编程(OOP)的概念,但它通过组合和一些高级特性(如 trait 和泛型)实现了类似 OOP 的功能。
定义结构体 定义结构体:使用 struct 关键字定义结构体。
struct Person {
name: String,
age: u32,
}
impl Person {
fn new(name: String, age: u32) -> Self {
Person { name, age }
}
}
fn main() {
let person = Person::new(String::from("Alice"), 30);
println!("Name: {}, Age: {}", person.name, person.age);
}
实现方法 实现方法:使用 impl 关键字为结构体实现方法。
struct Person {
name: String,
age: u32,
}
impl Person {
fn new(name: String, age: u32) -> Self {
Person { name, age }
}
fn introduce(&self) {
println!("Hello, my name is {} and I am {} years old.", self.name, self.age);
}
}
fn main() {
let person = Person::new(String::from("Alice"), 30);
person.introduce();
}
定义 Trait 定义 Trait:使用 trait 关键字定义一组行为。
trait Animal {
fn make_sound(&self);
}
struct Dog {
name: String,
}
impl Animal for Dog {
fn make_sound(&self) {
println!("Woof!");
}
}
struct Cat {
name: String,
}
impl Animal for Cat {
fn make_sound(&self) {
println!("Meow!");
}
}
fn make_animal_sound(animal: &dyn Animal) {
animal.make_sound();
}
fn main() {
let dog = Dog { name: String::from("Buddy") };
let cat = Cat { name: String::from("Whiskers") };
make_an animal_sound(&dog);
make_animal_sound(&cat);
}
泛型
泛型:使用 <T>
关键字定义泛型类型。
struct Box<T>(T);
impl<T> Box<T> {
fn new(item: T) -> Self {
Box(item)
}
}
fn main() {
let box_i32 = Box::new(5);
let box_str = Box::new(String::from("Hello"));
}
生命周期 生命周期:确保借用不会超出作用域。
struct Message<'a> {
text: &'a str,
}
impl<'a> Message<'a> {
fn new(text: &'a str) -> Self {
Message { text }
}
fn display(&self) {
println!("Message: {}", self.text);
}
}
fn main() {
let text = String::from("Hello, world!");
let message = Message::new(&text);
message.display();
}
单例模式 单例模式:确保一个类只有一个实例,并提供一个全局访问点。
struct Singleton {
instance: Option<Box<Self>>,
}
impl Singleton {
fn new() -> Self {
Singleton { instance: None }
}
fn get_instance() -> &'static Self {
static INSTANCE: Singleton = Singleton::new();
&INSTANCE
}
fn do_something(&self) {
println!("Doing something...");
}
}
fn main() {
let singleton = Singleton::get_instance();
singleton.do_something();
}
工厂模式 工厂模式:提供一个创建一系列相关或依赖对象的接口。
trait Shape {
fn draw(&self);
}
struct Circle;
impl Shape for Circle {
fn draw(&self) {
println!("Drawing a circle");
}
}
struct Square;
impl Shape for Square {
fn draw(&self) {
println!("Drawing a square");
}
}
struct ShapeFactory;
impl ShapeFactory {
fn create_shape(shape_type: &str) -> Box<dyn Shape> {
match shape_type {
"circle" => Box::new(Circle),
"square" => Box::new(Square),
_ => panic!("Unknown shape type"),
}
}
}
fn main() {
let circle = ShapeFactory::create_shape("circle");
let square = ShapeFactory::create_shape("square");
circle.draw();
square.draw();
}
观察者模式 观察者模式:定义对象间的一种一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。
trait Observer {
fn update(&self, message: String);
}
struct Subject {
observers: Vec<Box<dyn Observer>>,
}
impl Subject {
fn new() -> Self {
Subject {
observers: Vec::new(),
}
}
fn attach(&mut self, observer: Box<dyn Observer>) {
self.observers.push(observer);
}
fn detach(&mut self, observer: &Box<dyn Observer>) {
if let Some(index) = self.observers.iter().position(|o| o as *const dyn Observer == observer as *const dyn Observer) {
self.observers.remove(index);
}
}
fn notify(&self, message: String) {
for observer in &self.observers {
observer.update(message.clone());
}
}
}
struct ConcreteObserver {
name: String,
}
impl Observer for ConcreteObserver {
fn update(&self, message: String) {
println!("Observer {}: {}", self.name, message);
}
}
fn main() {
let subject = Subject::new();
let observer1 = Box::new(ConcreteObserver { name: String::from("Observer 1") });
let observer2 = Box::new(ConcreteObserver { name: String::from("Observer 2") });
subject.attach(observer1.clone());
subject.attach(observer2.clone());
subject.notify(String::from("Hello, world!"));
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!