Rust作为一门现代系统编程语言,以其独特的内存安全性和零成本抽象著称。其设计模式不仅体现了软件工程的通用智慧,更深度融合了Rust特有的所有权、借用检查和生命周期概念。本文将探讨Rust中几种关键的设计模式及其如何帮助开发者编写安全高效的代码。
设计模式在Rust中的重要性
设计模式在Rust编程语言中具有特殊的重要意义。Rust的所有权系统、生命周期和特质特性为传统设计模式提供了新的实现方式和思考角度。由于Rust的内存安全保证和零成本抽象原则,许多经典设计模式在Rust中需要重新构思和调整,这既带来了挑战也创造了机会。
Rust的设计模式不仅仅是解决常见问题的模板,更是对语言特性的深入理解和应用。通过恰当运用设计模式,开发者可以编写出既安全又高效的Rust代码,同时保持代码的可维护性和可扩展性。
创建型模式
建造者模式
建造者模式在Rust中特别流行,主要用于构造复杂对象。Rust的类型系统和所有权机制使得建造者模式实现更加安全和直观。
#[derive(Debug, Clone)]
pub struct DatabaseConfig {
host: String,
port: u16,
username: String,
password: String,
database_name: String,
max_connections: u32,
timeout_seconds: u64,
}
pub struct DatabaseConfigBuilder {
host: Option<String>,
port: Option<u16>,
username: Option<String>,
password: Option<String>,
database_name: Option<String>,
max_connections: Option<u32>,
timeout_seconds: Option<u64>,
}
impl DatabaseConfigBuilder {
pub fn new() -> Self {
Self {
host: None,
port: None,
username: None,
password: None,
database_name: None,
max_connections: None,
timeout_seconds: None,
}
}
pub fn host(mut self, host: String) -> Self {
self.host = Some(host);
self
}
pub fn port(mut self, port: u16) -> Self {
self.port = Some(port);
self
}
pub fn username(mut self, username: String) -> Self {
self.username = Some(username);
self
}
pub fn password(mut self, password: String) -> Self {
self.password = Some(password);
self
}
pub fn database_name(mut self, database_name: String) -> Self {
self.database_name = Some(database_name);
self
}
pub fn max_connections(mut self, max_connections: u32) -> Self {
self.max_connections = Some(max_connections);
self
}
pub fn timeout_seconds(mut self, timeout_seconds: u64) -> Self {
self.timeout_seconds = Some(timeout_seconds);
self
}
pub fn build(self) -> Result<DatabaseConfig, String> {
Ok(DatabaseConfig {
host: self.host.ok_or("Host is required")?,
port: self.port.ok_or("Port is required")?,
username: self.username.ok_or("Username is required")?,
password: self.password.ok_or("Password is required")?,
database_name: self.database_name.ok_or("Database name is required")?,
max_connections: self.max_connections.unwrap_or(10),
timeout_seconds: self.timeout_seconds.unwrap_or(30),
})
}
}
impl DatabaseConfig {
pub fn builder() -> DatabaseConfigBuilder {
DatabaseConfigBuilder::new()
}
}
// 使用示例
fn main() -> Result<(), String> {
let config = DatabaseConfig::builder()
.host("localhost".to_string())
.port(5432)
.username("admin".to_string())
.password("secret".to_string())
.database_name("myapp".to_string())
.max_connections(20)
.timeout_seconds(60)
.build()?;
println!("Database config: {:?}", config);
Ok(())
}
工厂模式
Rust中的工厂模式通常结合特质和枚举来实现,提供灵活的对象创建机制。
pub trait Document {
fn open(&self);
fn save(&self);
fn close(&self);
}
pub struct TextDocument;
impl Document for TextDocument {
fn open(&self) {
println!("Opening text document");
}
fn save(&self) {
println!("Saving text document");
}
fn close(&self) {
println!("Closing text document");
}
}
pub struct SpreadsheetDocument;
impl Document for SpreadsheetDocument {
fn open(&self) {
println!("Opening spreadsheet document");
}
fn save(&self) {
println!("Saving spreadsheet document");
}
fn close(&self) {
println!("Closing spreadsheet document");
}
}
pub struct PresentationDocument;
impl Document for PresentationDocument {
fn open(&self) {
println!("Opening presentation document");
}
fn save(&self) {
println!("Saving presentation document");
}
fn close(&self) {
println!("Closing presentation document");
}
}
pub enum DocumentType {
Text,
Spreadsheet,
Presentation,
}
pub struct DocumentFactory;
impl DocumentFactory {
pub fn create_document(doc_type: DocumentType) -> Box<dyn Document> {
match doc_type {
DocumentType::Text => Box::new(TextDocument),
DocumentType::Spreadsheet => Box::new(SpreadsheetDocument),
DocumentType::Presentation => Box::new(PresentationDocument),
}
}
}
// 使用示例
fn main() {
let documents = vec![
DocumentType::Text,
DocumentType::Spreadsheet,
DocumentType::Presentation,
];
for doc_type in documents {
let document = DocumentFactory::create_document(doc_type);
document.open();
document.save();
document.close();
println!("---");
}
}
单例模式
在Rust中实现单例模式需要考虑线程安全和所有权问题,通常使用OnceLock或Mutex来实现。
use std::sync::{Mutex, OnceLock};
use std::collections::HashMap;
pub struct ConfigurationManager {
settings: Mutex<HashMap<String, String>>,
}
impl ConfigurationManager {
fn new() -> Self {
let mut settings = HashMap::new();
settings.insert("database_url".to_string(), "postgresql://localhost:5432".to_string());
settings.insert("max_connections".to_string(), "100".to_string());
settings.insert("timeout".to_string(), "30".to_string());
Self {
settings: Mutex::new(settings),
}
}
pub fn global() -> &'static Self {
static INSTANCE: OnceLock<ConfigurationManager> = OnceLock::new();
INSTANCE.get_or_init(|| ConfigurationManager::new())
}
pub fn get_setting(&self, key: &str) -> Option<String> {
let settings = self.settings.lock().unwrap();
settings.get(key).cloned()
}
pub fn set_setting(&self, key: String, value: String) {
let mut settings = self.settings.lock().unwrap();
settings.insert(key, value);
}
pub fn list_settings(&self) -> HashMap<String, String> {
let settings = self.settings.lock().unwrap();
settings.clone()
}
}
// 使用示例
fn main() {
// 获取单例实例
let config = ConfigurationManager::global();
// 读取配置
if let Some(db_url) = config.get_setting("database_url") {
println!("Database URL: {}", db_url);
}
// 修改配置
config.set_setting("timeout".to_string(), "60".to_string());
// 列出所有配置
let all_settings = config.list_settings();
println!("All settings: {:?}", all_settings);
// 验证确实是同一个实例
let config2 = ConfigurationManager::global();
assert!(std::ptr::eq(config, config2));
}
结构型模式
适配器模式
适配器模式在Rust中常用于使不兼容的接口能够协同工作。
// 旧系统的日志接口
pub trait LegacyLogger {
fn log_message(&self, level: u8, message: &str);
}
pub struct FileLogger;
impl LegacyLogger for FileLogger {
fn log_message(&self, level: u8, message: &str) {
let level_str = match level {
1 => "ERROR",
2 => "WARN",
3 => "INFO",
_ => "DEBUG",
};
println!("[{}] {} - {}", level_str, chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), message);
}
}
// 新系统的日志接口
pub trait ModernLogger {
fn error(&self, message: &str);
fn warn(&self, message: &str);
fn info(&self, message: &str);
fn debug(&self, message: &str);
}
// 适配器,让旧日志接口适配新系统
pub struct LoggerAdapter<T: LegacyLogger> {
legacy_logger: T,
}
impl<T: LegacyLogger> LoggerAdapter<T> {
pub fn new(legacy_logger: T) -> Self {
Self { legacy_logger }
}
}
impl<T: LegacyLogger> ModernLogger for LoggerAdapter<T> {
fn error(&self, message: &str) {
self.legacy_logger.log_message(1, message);
}
fn warn(&self, message: &str) {
self.legacy_logger.log_message(2, message);
}
fn info(&self, message: &str) {
self.legacy_logger.log_message(3, message);
}
fn debug(&self, message: &str) {
self.legacy_logger.log_message(4, message);
}
}
// 新系统的应用
pub struct Application<T: ModernLogger> {
logger: T,
}
impl<T: ModernLogger> Application<T> {
pub fn new(logger: T) -> Self {
Self { logger }
}
pub fn run(&self) {
self.logger.info("Application starting");
self.logger.debug("Loading configuration");
self.logger.warn("Deprecated feature used");
self.logger.error("Something went wrong");
self.logger.info("Application shutting down");
}
}
// 使用示例
fn main() {
let legacy_logger = FileLogger;
let adapter = LoggerAdapter::new(legacy_logger);
let app = Application::new(adapter);
app.run();
}
装饰器模式
Rust中的装饰器模式通常通过组合和特质来实现,为对象动态添加功能。
pub trait DataProcessor {
fn process(&self, data: &str) -> String;
}
// 基础处理器
pub struct BasicProcessor;
impl DataProcessor for BasicProcessor {
fn process(&self, data: &str) -> String {
data.to_string()
}
}
// 装饰器:加密处理
pub struct EncryptionDecorator<T: DataProcessor> {
processor: T,
key: String,
}
impl<T: DataProcessor> EncryptionDecorator<T> {
pub fn new(processor: T, key: String) -> Self {
Self { processor, key }
}
fn encrypt(&self, data: &str) -> String {
// 简单的XOR加密示例
let encrypted: String = data
.chars()
.zip(self.key.chars().cycle())
.map(|(c, k)| (c as u8 ^ k as u8) as char)
.collect();
format!("ENCRYPTED[{}]", encrypted)
}
}
impl<T: DataProcessor> DataProcessor for EncryptionDecorator<T> {
fn process(&self, data: &str) -> String {
let processed = self.processor.process(data);
self.encrypt(&processed)
}
}
// 装饰器:压缩处理
pub struct CompressionDecorator<T: DataProcessor> {
processor: T,
}
impl<T: DataProcessor> CompressionDecorator<T> {
pub fn new(processor: T) -> Self {
Self { processor }
}
fn compress(&self, data: &str) -> String {
// 简单的压缩示例(实际项目中会使用真正的压缩算法)
if data.len() > 50 {
format!("COMPRESSED[{}...]", &data[..50])
} else {
format!("COMPRESSED[{}]", data)
}
}
}
impl<T: DataProcessor> DataProcessor for CompressionDecorator<T> {
fn process(&self, data: &str) -> String {
let processed = self.processor.process(data);
self.compress(&processed)
}
}
// 装饰器:编码处理
pub struct EncodingDecorator<T: DataProcessor> {
processor: T,
}
impl<T: DataProcessor> EncodingDecorator<T> {
pub fn new(processor: T) -> Self {
Self { processor }
}
fn encode(&self, data: &str) -> String {
format!("BASE64[{}]", data)
}
}
impl<T: DataProcessor> DataProcessor for EncodingDecorator<T> {
fn process(&self, data: &str) -> String {
let processed = self.processor.process(data);
self.encode(&processed)
}
}
// 使用示例
fn main() {
let processor = BasicProcessor;
// 单独使用基础处理器
let result1 = processor.process("Hello, World!");
println!("Basic: {}", result1);
// 使用加密装饰器
let encrypted_processor = EncryptionDecorator::new(processor, "secret".to_string());
let result2 = encrypted_processor.process("Hello, World!");
println!("Encrypted: {}", result2);
// 组合多个装饰器
let basic = BasicProcessor;
let compressed = CompressionDecorator::new(basic);
let encoded = EncodingDecorator::new(compressed);
let encrypted = EncryptionDecorator::new(encoded, "key".to_string());
let long_text = "This is a very long text that needs to be processed through multiple decorators to demonstrate the power of the decorator pattern in Rust.";
let result3 = encrypted.process(long_text);
println!("Fully decorated: {}", result3);
}
外观模式
外观模式为复杂子系统提供简化的接口。
pub struct CPU;
impl CPU {
pub fn start(&self) {
println!("CPU starting...");
}
pub fn execute(&self) {
println!("CPU executing instructions...");
}
pub fn shutdown(&self) {
println!("CPU shutting down...");
}
}
pub struct Memory;
impl Memory {
pub fn load(&self) {
println!("Memory loading data...");
}
pub fn free(&self) {
println!("Memory freeing resources...");
}
}
pub struct HardDrive;
impl HardDrive {
pub fn read(&self) {
println!("Hard drive reading data...");
}
pub fn write(&self) {
println!("Hard drive writing data...");
}
}
pub struct GraphicsCard;
impl GraphicsCard {
pub fn initialize(&self) {
println!("Graphics card initializing...");
}
pub fn render(&self) {
println!("Graphics card rendering...");
}
pub fn shutdown(&self) {
println!("Graphics card shutting down...");
}
}
// 外观:计算机系统
pub struct ComputerFacade {
cpu: CPU,
memory: Memory,
hard_drive: HardDrive,
graphics_card: GraphicsCard,
}
impl ComputerFacade {
pub fn new() -> Self {
Self {
cpu: CPU,
memory: Memory,
hard_drive: HardDrive,
graphics_card: GraphicsCard,
}
}
pub fn start_computer(&self) {
println!("=== Starting Computer ===");
self.cpu.start();
self.memory.load();
self.hard_drive.read();
self.graphics_card.initialize();
println!("=== Computer Started ===\n");
}
pub fn run_program(&self) {
println!("=== Running Program ===");
self.cpu.execute();
self.graphics_card.render();
self.hard_drive.read();
self.hard_drive.write();
println!("=== Program Completed ===\n");
}
pub fn shutdown_computer(&self) {
println!("=== Shutting Down Computer ===");
self.graphics_card.shutdown();
self.hard_drive.write();
self.memory.free();
self.cpu.shutdown();
println!("=== Computer Shutdown ===\n");
}
}
// 使用示例
fn main() {
let computer = ComputerFacade::new();
// 用户只需要调用简单的接口,不需要了解底层复杂子系统
computer.start_computer();
computer.run_program();
computer.shutdown_computer();
}
行为型模式
策略模式
策略模式允许在运行时选择算法。
pub trait PaymentStrategy {
fn pay(&self, amount: f64) -> Result<(), String>;
}
pub struct CreditCardPayment {
card_number: String,
expiry_date: String,
cvv: String,
}
impl CreditCardPayment {
pub fn new(card_number: String, expiry_date: String, cvv: String) -> Self {
Self {
card_number,
expiry_date,
cvv,
}
}
}
impl PaymentStrategy for CreditCardPayment {
fn pay(&self, amount: f64) -> Result<(), String> {
println!("Processing credit card payment of ${:.2}", amount);
println!("Card: {}***", &self.card_number[..4]);
// 实际项目中这里会有真实的支付处理逻辑
Ok(())
}
}
pub struct PayPalPayment {
email: String,
}
impl PayPalPayment {
pub fn new(email: String) -> Self {
Self { email }
}
}
impl PaymentStrategy for PayPalPayment {
fn pay(&self, amount: f64) -> Result<(), String> {
println!("Processing PayPal payment of ${:.2}", amount);
println!("Email: {}", self.email);
// 实际项目中这里会有真实的PayPal支付逻辑
Ok(())
}
}
pub struct CryptoPayment {
wallet_address: String,
}
impl CryptoPayment {
pub fn new(wallet_address: String) -> Self {
Self { wallet_address }
}
}
impl PaymentStrategy for CryptoPayment {
fn pay(&self, amount: f64) -> Result<(), String> {
println!("Processing cryptocurrency payment of ${:.2}", amount);
println!("Wallet: {}...", &self.wallet_address[..8]);
// 实际项目中这里会有真实的加密货币支付逻辑
Ok(())
}
}
pub struct PaymentProcessor {
strategy: Box<dyn PaymentStrategy>,
}
impl PaymentProcessor {
pub fn new(strategy: Box<dyn PaymentStrategy>) -> Self {
Self { strategy }
}
pub fn set_strategy(&mut self, strategy: Box<dyn PaymentStrategy>) {
self.strategy = strategy;
}
pub fn process_payment(&self, amount: f64) -> Result<(), String> {
self.strategy.pay(amount)
}
}
// 使用示例
fn main() -> Result<(), String> {
let credit_card = CreditCardPayment::new(
"1234567812345678".to_string(),
"12/25".to_string(),
"123".to_string(),
);
let paypal = PayPalPayment::new("user@example.com".to_string());
let crypto = CryptoPayment::new("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa".to_string());
let mut processor = PaymentProcessor::new(Box::new(credit_card));
// 使用信用卡支付
processor.process_payment(100.0)?;
// 切换到PayPal支付
processor.set_strategy(Box::new(paypal));
processor.process_payment(50.0)?;
// 切换到加密货币支付
processor.set_strategy(Box::new(crypto));
processor.process_payment(75.0)?;
Ok(())
}
观察者模式
观察者模式在Rust中通常使用通道或回调函数实现。
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
pub type Event = String;
pub type SubscriberId = u64;
pub type Callback = Box<dyn Fn(&Event) + Send + Sync>;
pub struct EventBus {
subscribers: Arc<Mutex<HashMap<Event, HashMap<SubscriberId, Callback>>>>,
next_id: Arc<Mutex<SubscriberId>>,
}
impl EventBus {
pub fn new() -> Self {
Self {
subscribers: Arc::new(Mutex::new(HashMap::new())),
next_id: Arc::new(Mutex::new(0)),
}
}
pub fn subscribe<F>(&self, event: Event, callback: F) -> SubscriberId
where
F: Fn(&Event) + Send + Sync + 'static,
{
let mut subscribers = self.subscribers.lock().unwrap();
let mut next_id = self.next_id.lock().unwrap();
let id = *next_id;
*next_id += 1;
subscribers
.entry(event)
.or_insert_with(HashMap::new)
.insert(id, Box::new(callback));
id
}
pub fn unsubscribe(&self, event: &Event, id: SubscriberId) {
let mut subscribers = self.subscribers.lock().unwrap();
if let Some(event_subscribers) = subscribers.get_mut(event) {
event_subscribers.remove(&id);
}
}
pub fn publish(&self, event: Event) {
let subscribers = self.subscribers.lock().unwrap();
if let Some(event_subscribers) = subscribers.get(&event) {
for callback in event_subscribers.values() {
callback(&event);
}
}
}
}
// 发布者
pub struct Publisher {
event_bus: Arc<EventBus>,
}
impl Publisher {
pub fn new(event_bus: Arc<EventBus>) -> Self {
Self { event_bus }
}
pub fn publish_event(&self, event: Event) {
println!("Publisher: Publishing event '{}'", event);
self.event_bus.publish(event);
}
}
// 订阅者
pub struct Subscriber {
id: SubscriberId,
event_bus: Arc<EventBus>,
event: Event,
}
impl Subscriber {
pub fn new(event_bus: Arc<EventBus>, event: Event, name: String) -> Self {
let id = event_bus.subscribe(event.clone(), move |e| {
println!("Subscriber {}: Received event '{}'", name, e);
});
Self {
id,
event_bus,
event,
}
}
}
impl Drop for Subscriber {
fn drop(&mut self) {
self.event_bus.unsubscribe(&self.event, self.id);
}
}
// 使用示例
fn main() {
let event_bus = Arc::new(EventBus::new());
let publisher = Publisher::new(event_bus.clone());
// 创建订阅者
let subscriber1 = Subscriber::new(
event_bus.clone(),
"user.created".to_string(),
"UserLogger".to_string(),
);
let subscriber2 = Subscriber::new(
event_bus.clone(),
"user.created".to_string(),
"EmailService".to_string(),
);
let subscriber3 = Subscriber::new(
event_bus.clone(),
"order.placed".to_string(),
"InventoryService".to_string(),
);
// 发布事件
publisher.publish_event("user.created".to_string());
publisher.publish_event("order.placed".to_string());
publisher.publish_event("user.updated".to_string());
// 订阅者在离开作用域时会自动取消订阅
}
状态模式
状态模式在Rust中通常使用枚举或特质对象实现。
pub trait VendingState {
fn insert_coin(self: Box<Self>) -> Result<Box<dyn VendingState>, String>;
fn select_item(self: Box<Self>) -> Result<Box<dyn VendingState>, String>;
fn dispense_item(self: Box<Self>) -> Result<Box<dyn VendingState>, String>;
fn state_name(&self) -> &str;
}
// 等待投币状态
pub struct WaitingForCoinState;
impl VendingState for WaitingForCoinState {
fn insert_coin(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
println!("Coin inserted. You can now select an item.");
Ok(Box::new(HasCoinState))
}
fn select_item(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
Err("Please insert a coin first".to_string())
}
fn dispense_item(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
Err("Please insert a coin and select an item first".to_string())
}
fn state_name(&self) -> &str {
"WaitingForCoin"
}
}
// 已投币状态
pub struct HasCoinState;
impl VendingState for HasCoinState {
fn insert_coin(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
Err("Coin already inserted. Please select an item.".to_string())
}
fn select_item(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
println!("Item selected. Preparing to dispense.");
Ok(Box::new(DispensingState))
}
fn dispense_item(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
Err("Please select an item first".to_string())
}
fn state_name(&self) -> &str {
"HasCoin"
}
}
// 分发商品状态
pub struct DispensingState;
impl VendingState for DispensingState {
fn insert_coin(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
Err("Dispensing in progress. Please wait.".to_string())
}
fn select_item(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
Err("Dispensing in progress. Please wait.".to_string())
}
fn dispense_item(self: Box<Self>) -> Result<Box<dyn VendingState>, String> {
println!("Item dispensed. Thank you for your purchase!");
Ok(Box::new(WaitingForCoinState))
}
fn state_name(&self) -> &str {
"Dispensing"
}
}
// 自动售货机
pub struct VendingMachine {
state: Box<dyn VendingState>,
}
impl VendingMachine {
pub fn new() -> Self {
Self {
state: Box::new(WaitingForCoinState),
}
}
pub fn insert_coin(&mut self) -> Result<(), String> {
println!("Current state: {}", self.state.state_name());
self.state = self.state.insert_coin()?;
Ok(())
}
pub fn select_item(&mut self) -> Result<(), String> {
println!("Current state: {}", self.state.state_name());
self.state = self.state.select_item()?;
Ok(())
}
pub fn dispense_item(&mut self) -> Result<(), String> {
println!("Current state: {}", self.state.state_name());
self.state = self.state.dispense_item()?;
Ok(())
}
pub fn current_state(&self) -> &str {
self.state.state_name()
}
}
// 使用示例
fn main() {
let mut machine = VendingMachine::new();
// 测试正常流程
println!("=== Testing normal flow ===");
assert_eq!(machine.current_state(), "WaitingForCoin");
machine.insert_coin().unwrap();
assert_eq!(machine.current_state(), "HasCoin");
machine.select_item().unwrap();
assert_eq!(machine.current_state(), "Dispensing");
machine.dispense_item().unwrap();
assert_eq!(machine.current_state(), "WaitingForCoin");
println!("\n=== Testing error flow ===");
// 测试错误流程:未投币就选择商品
let mut machine2 = VendingMachine::new();
let result = machine2.select_item();
assert!(result.is_err());
println!("Error: {}", result.unwrap_err());
}
Rust特有的模式
Newtype模式
Newtype模式是Rust中常用的包装模式,用于提供类型安全和抽象。
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub struct Email(String);
impl Email {
pub fn new(email: &str) -> Result<Self, String> {
if email.contains('@') && email.contains('.') {
Ok(Self(email.to_string()))
} else {
Err("Invalid email format".to_string())
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Email {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct UserId(u64);
impl UserId {
pub fn new(id: u64) -> Self {
Self(id)
}
pub fn value(&self) -> u64 {
self.0
}
}
impl fmt::Display for UserId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Clone)]
pub struct User {
id: UserId,
email: Email,
username: String,
}
impl User {
pub fn new(id: u64, email: &str, username: &str) -> Result<Self, String> {
Ok(Self {
id: UserId::new(id),
email: Email::new(email)?,
username: username.to_string(),
})
}
pub fn id(&self) -> &UserId {
&self.id
}
pub fn email(&self) -> &Email {
&self.email
}
pub fn username(&self) -> &str {
&self.username
}
}
// 使用示例
fn main() -> Result<(), String> {
let user = User::new(1, "alice@example.com", "alice")?;
println!("User ID: {}", user.id());
println!("Email: {}", user.email());
println!("Username: {}", user.username());
// 类型安全:不能直接比较不同类型的newtype
let email = Email::new("bob@example.com")?;
// 下面的代码会编译错误,因为UserId和Email是不同的类型
// assert_eq!(user.id(), &email);
Ok(())
}
RAII模式
RAII(Resource Acquisition Is Initialization)是Rust的核心模式,通过所有权系统自动管理资源。
use std::fs::File;
use std::io::{self, Write, Read};
use std::path::Path;
// 自定义文件处理器,实现RAII
pub struct ManagedFile {
file: Option<File>,
filename: String,
}
impl ManagedFile {
pub fn new<P: AsRef<Path>>(filename: P) -> io::Result<Self> {
let file = File::create(&filename)?;
Ok(Self {
file: Some(file),
filename: filename.as_ref().to_string_lossy().to_string(),
})
}
pub fn write(&mut self, content: &str) -> io::Result<()> {
if let Some(file) = &mut self.file {
file.write_all(content.as_bytes())?;
Ok(())
} else {
Err(io::Error::new(io::ErrorKind::Other, "File is closed"))
}
}
pub fn read_to_string(&mut self) -> io::Result<String> {
if let Some(file) = &mut self.file {
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
} else {
Err(io::Error::new(io::ErrorKind::Other, "File is closed"))
}
}
pub fn close(&mut self) -> io::Result<()> {
if let Some(file) = self.file.take() {
// File在drop时自动关闭,这里只是演示
println!("Closing file: {}", self.filename);
drop(file);
}
Ok(())
}
}
impl Drop for ManagedFile {
fn drop(&mut self) {
if self.file.is_some() {
println!("Automatically closing file: {} (RAII)", self.filename);
let _ = self.close();
}
}
}
// 互斥锁的RAII包装器
pub struct ScopedLock<'a, T> {
data: &'a mut T,
lock_name: String,
}
impl<'a, T> ScopedLock<'a, T> {
pub fn new(data: &'a mut T, lock_name: &str) -> Self {
println!("Acquiring lock: {}", lock_name);
Self {
data,
lock_name: lock_name.to_string(),
}
}
pub fn data(&mut self) -> &mut T {
self.data
}
}
impl<'a, T> Drop for ScopedLock<'a, T> {
fn drop(&mut self) {
println!("Releasing lock: {}", self.lock_name);
}
}
// 使用示例
fn main() -> io::Result<()> {
// 文件RAII示例
{
let mut file = ManagedFile::new("example.txt")?;
file.write("Hello, RAII pattern!")?;
// 文件在离开作用域时自动关闭
}
// 互斥锁RAII示例
{
let mut shared_data = vec![1, 2, 3];
println!("Before lock: {:?}", shared_data);
{
let mut lock = ScopedLock::new(&mut shared_data, "data_lock");
lock.data().push(4);
println!("Inside lock: {:?}", lock.data());
} // 锁在这里自动释放
println!("After lock: {:?}", shared_data);
}
Ok(())
}
并发模式
Actor模式
Actor模式在Rust中常用于构建并发系统。
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
pub enum Message {
Increment(u32),
Decrement(u32),
GetCount(mpsc::Sender<u32>),
Shutdown,
}
pub struct CounterActor {
count: u32,
receiver: mpsc::Receiver<Message>,
}
impl CounterActor {
pub fn new(receiver: mpsc::Receiver<Message>) -> Self {
Self {
count: 0,
receiver,
}
}
pub fn run(mut self) {
while let Ok(message) = self.receiver.recv() {
match message {
Message::Increment(amount) => {
self.count += amount;
println!("Counter incremented to: {}", self.count);
}
Message::Decrement(amount) => {
if amount <= self.count {
self.count -= amount;
} else {
self.count = 0;
}
println!("Counter decremented to: {}", self.count);
}
Message::GetCount(sender) => {
let _ = sender.send(self.count);
}
Message::Shutdown => {
println!("Counter actor shutting down");
break;
}
}
}
}
}
pub struct CounterHandle {
sender: mpsc::Sender<Message>,
}
impl CounterHandle {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel();
let actor = CounterActor::new(receiver);
thread::spawn(move || {
actor.run();
});
Self { sender }
}
pub fn increment(&self, amount: u32) {
let _ = self.sender.send(Message::Increment(amount));
}
pub fn decrement(&self, amount: u32) {
let _ = self.sender.send(Message::Decrement(amount));
}
pub fn get_count(&self) -> Option<u32> {
let (sender, receiver) = mpsc::channel();
let _ = self.sender.send(Message::GetCount(sender));
receiver.recv().ok()
}
pub fn shutdown(self) {
let _ = self.sender.send(Message::Shutdown);
}
}
// 使用示例
fn main() {
let counter = CounterHandle::new();
// 发送多个操作
counter.increment(5);
counter.increment(3);
counter.decrement(2);
// 等待操作完成
thread::sleep(Duration::from_millis(100));
// 获取当前计数
if let Some(count) = counter.get_count() {
println!("Current count: {}", count);
}
// 继续操作
counter.increment(10);
counter.decrement(1);
thread::sleep(Duration::from_millis(100));
if let Some(count) = counter.get_count() {
println!("Final count: {}", count);
}
// 关闭actor
counter.shutdown();
}
错误处理模式
组合错误类型
Rust中常用的错误处理模式,使用自定义错误类型和错误转换。
use std::fmt;
use std::io;
use std::num::ParseIntError;
#[derive(Debug)]
pub enum ApplicationError {
IoError(io::Error),
ParseError(ParseIntError),
ValidationError(String),
BusinessLogicError(String),
}
impl fmt::Display for ApplicationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ApplicationError::IoError(e) => write!(f, "IO error: {}", e),
ApplicationError::ParseError(e) => write!(f, "Parse error: {}", e),
ApplicationError::ValidationError(e) => write!(f, "Validation error: {}", e),
ApplicationError::BusinessLogicError(e) => write!(f, "Business logic error: {}", e),
}
}
}
impl std::error::Error for ApplicationError {}
impl From<io::Error> for ApplicationError {
fn from(error: io::Error) -> Self {
ApplicationError::IoError(error)
}
}
impl From<ParseIntError> for ApplicationError {
fn from(error: ParseIntError) -> Self {
ApplicationError::ParseError(error)
}
}
pub struct UserService;
impl UserService {
pub fn validate_age(age_str: &str) -> Result<u8, ApplicationError> {
let age: u8 = age_str.parse()?;
if age < 18 {
Err(ApplicationError::ValidationError(
"User must be at least 18 years old".to_string(),
))
} else if age > 120 {
Err(ApplicationError::ValidationError(
"Age must be reasonable".to_string(),
))
} else {
Ok(age)
}
}
pub fn create_user(name: &str, age_str: &str) -> Result<String, ApplicationError> {
if name.is_empty() {
return Err(ApplicationError::ValidationError(
"Name cannot be empty".to_string(),
));
}
let age = Self::validate_age(age_str)?;
if name == "admin" {
return Err(ApplicationError::BusinessLogicError(
"Admin user cannot be created this way".to_string(),
));
}
Ok(format!("User '{}' (age: {}) created successfully", name, age))
}
}
// 使用示例
fn main() {
let test_cases = vec![
("", "25"),
("alice", "17"),
("admin", "30"),
("bob", "150"),
("charlie", "invalid"),
("david", "25"),
];
for (name, age) in test_cases {
match UserService::create_user(name, age) {
Ok(success) => println!("✓ {}", success),
Err(error) => println!("✗ Error for {} (age: {}): {}", name, age, error),
}
}
}
模式匹配与枚举设计
Rust的模式匹配能力为设计模式提供了强大的支持。
#[derive(Debug, Clone)]
pub enum PaymentMethod {
CreditCard {
number: String,
expiry: String,
cvv: String,
},
PayPal {
email: String,
},
Cryptocurrency {
wallet_address: String,
currency: CryptoCurrency,
},
BankTransfer {
account_number: String,
routing_number: String,
},
}
#[derive(Debug, Clone)]
pub enum CryptoCurrency {
Bitcoin,
Ethereum,
Litecoin,
Other(String),
}
#[derive(Debug)]
pub struct Payment {
amount: f64,
method: PaymentMethod,
description: String,
}
impl Payment {
pub fn new(amount: f64, method: PaymentMethod, description: String) -> Self {
Self {
amount,
method,
description,
}
}
pub fn process(&self) -> Result<String, String> {
match &self.method {
PaymentMethod::CreditCard { number, expiry, cvv } => {
if number.len() != 16 {
return Err("Invalid credit card number".to_string());
}
if cvv.len() != 3 {
return Err("Invalid CVV".to_string());
}
Ok(format!(
"Processed credit card payment of ${:.2} for {}",
self.amount, self.description
))
}
PaymentMethod::PayPal { email } => {
if !email.contains('@') {
return Err("Invalid email address".to_string());
}
Ok(format!(
"Processed PayPal payment of ${:.2} for {}",
self.amount, self.description
))
}
PaymentMethod::Cryptocurrency { wallet_address, currency } => {
if wallet_address.len() < 10 {
return Err("Invalid wallet address".to_string());
}
let currency_str = match currency {
CryptoCurrency::Bitcoin => "BTC",
CryptoCurrency::Ethereum => "ETH",
CryptoCurrency::Litecoin => "LTC",
CryptoCurrency::Other(name) => name,
};
Ok(format!(
"Processed {} payment of ${:.2} for {}",
currency_str, self.amount, self.description
))
}
PaymentMethod::BankTransfer { account_number, routing_number } => {
if account_number.len() != 10 {
return Err("Invalid account number".to_string());
}
if routing_number.len() != 9 {
return Err("Invalid routing number".to_string());
}
Ok(format!(
"Processed bank transfer of ${:.2} for {}",
self.amount, self.description
))
}
}
}
pub fn get_fee(&self) -> f64 {
match &self.method {
PaymentMethod::CreditCard { .. } => self.amount * 0.03,
PaymentMethod::PayPal { .. } => self.amount * 0.025,
PaymentMethod::Cryptocurrency { currency, .. } => match currency {
CryptoCurrency::Bitcoin => self.amount * 0.01,
CryptoCurrency::Ethereum => self.amount * 0.015,
CryptoCurrency::Litecoin => self.amount * 0.02,
CryptoCurrency::Other(_) => self.amount * 0.025,
},
PaymentMethod::BankTransfer { .. } => 1.0, // 固定费用
}
}
}
// 使用示例
fn main() {
let payments = vec![
Payment::new(
100.0,
PaymentMethod::CreditCard {
number: "1234567812345678".to_string(),
expiry: "12/25".to_string(),
cvv: "123".to_string(),
},
"Online purchase".to_string(),
),
Payment::new(
50.0,
PaymentMethod::PayPal {
email: "user@example.com".to_string(),
},
"Subscription".to_string(),
),
Payment::new(
200.0,
PaymentMethod::Cryptocurrency {
wallet_address: "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa".to_string(),
currency: CryptoCurrency::Bitcoin,
},
"Large purchase".to_string(),
),
];
for payment in payments {
println!("Processing payment: {:?}", payment.method);
match payment.process() {
Ok(result) => {
println!("✓ {}", result);
println!(" Fee: ${:.2}", payment.get_fee());
}
Err(error) => {
println!("✗ Error: {}", error);
}
}
println!("---");
}
}
通过以上全面的示例,我们展示了Rust中各种设计模式的实现方式和应用场景。Rust的所有权系统、特质系统和模式匹配特性为传统设计模式提供了独特而强大的实现方式,同时也催生了一些Rust特有的模式。这些模式帮助开发者编写出安全、高效且可维护的Rust代码。