设计模式之适配器模式(rust实现)

  • 设计模式之适配器模式(Rust实现)
 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
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::fmt::Error;

// 适配器接口
trait Ftp {
    fn create_user(&self, username: &str) -> Result<(), Error>;
}

struct Vsftpd {}

// Vsftpd 创建用户方法
impl Vsftpd {
    fn vsftpd_create_user(&self, username: &str) -> Result<(), Error> {
        println!("Create user:{} success", username);
        Ok(())
    }
}

// Vsftpd 适配器
struct VsftpdAdapter {
    client: Vsftpd
}

// Vsftpd 实现适配器接口
impl Ftp for VsftpdAdapter {
    fn create_user(&self, username: &str) -> Result<(), Error> {
        self.client.vsftpd_create_user(username)
    }
}


struct Pureftpd {}

// Pureftpd 创建用户方法
impl Pureftpd {
    fn pureftpd_create_user(&self, username: &str) -> Result<(), Error> {
        println!("Create user:{} success", username);
        Ok(())
    }
}

// Pureftpd 适配器
struct PureftpdAdapter {
    client: Pureftpd
}

// Pureftpd 实现适配器方法
impl Ftp for PureftpdAdapter{
    fn create_user(&self, username: &str) -> Result<(), Error> {
        self.client.pureftpd_create_user(username)
    }
}

fn main() {
    let vsftpd = &VsftpdAdapter{client: Vsftpd{}};
    vsftpd.create_user("user1").unwrap();
    let pureftpd = &PureftpdAdapter{client: Pureftpd{}};
    pureftpd.create_user("user1").unwrap();
}
updatedupdated2024-10-012024-10-01