用Rust实现23种设计模式之 中介者模式

关注我,学习Rust不迷路!!

中介者模式是一种行为型设计模式,它通过引入一个中介者对象来协调多个对象之间的交互。中介者模式通过降低对象之间的直接耦合,提高了系统的可维护性和灵活性。以下是中介者模式的优点和使用场景:

优点:

  1. 减少耦合:中介者模式通过将对象之间的交互集中在中介者对象中,减少了对象之间的直接耦合,使得它们可以独立变化。
  2. 简化对象:中介者模式将对象之间的通信逻辑抽离到中介者对象中,使得各个对象可以专注于自身的职责,简化了对象的实现。
  3. 提高可维护性:由于对象之间的交互逻辑集中在中介者对象中,当系统需要修改交互逻辑时,只需要修改中介者对象而不影响其他对象。

使用场景:

  1. 当系统中的对象之间存在复杂的交互关系,导致对象之间的耦合度较高时,可以考虑使用中介者模式。
  2. 当一个对象的行为依赖于其他多个对象,并且这些对象之间的交互逻辑复杂且频繁发生变化时,可以考虑使用中介者模式。
  3. 当希望通过集中管理对象之间的交互,避免交互逻辑分散在各个对象中,提高系统的可维护性和灵活性时,可以考虑使用中介者模式。
    Rust实现中介者模式的代码示例:
    下面是一个使用Rust实现中介者模式的示例代码,带有详细的注释和说明:
// 定义中介者接口
trait Mediator {
    fn notify(&self, sender: &str, message: &str);
}
 // 实现具体中介者
struct ConcreteMediator {
    colleagues: Vec<Box<dyn Colleague>>,
}
 impl Mediator for ConcreteMediator {
    fn notify(&self, sender: &str, message: &str) {
        for colleague in &self.colleagues {
            if colleague.name() != sender {
                colleague.receive(message);
            }
        }
    }
}
 // 定义同事接口
trait Colleague {
    fn name(&self) -> &str;
    fn send(&self, mediator: &dyn Mediator, message: &str);
    fn receive(&self, message: &str);
}
 // 实现具体同事A
struct ConcreteColleagueA {
    name: String,
}
 impl Colleague for ConcreteColleagueA {
    fn name(&self) -> &str {
        &self.name
    }
     fn send(&self, mediator: &dyn Mediator, message: &str) {
        mediator.notify(&self.name, message);
    }
     fn receive(&self, message: &str) {
        println!("Colleague A received: {}", message);
    }
}
 // 实现具体同事B
struct ConcreteColleagueB {
    name: String,
}
 impl Colleague for ConcreteColleagueB {
    fn name(&self) -> &str {
        &self.name
    }
     fn send(&self, mediator: &dyn Mediator, message: &str) {
        mediator.notify(&self.name, message);
    }
     fn receive(&self, message: &str) {
        println!("Colleague B received: {}", message);
    }
}
 fn main() {
    // 创建具体中介者对象
    let mediator = Box::new(ConcreteMediator { colleagues: vec![] });
     // 创建具体同事对象
    let colleague_a = Box::new(ConcreteColleagueA { name: "Colleague A".to_string() });
    let colleague_b = Box::new(ConcreteColleagueB { name: "Colleague B".to_string() });
     // 注册同事到中介者
    mediator.colleagues.push(colleague_a);
    mediator.colleagues.push(colleague_b);
     // 同事A发送消息
    mediator.colleagues[0].send(&mediator, "Hello, Colleague B!");
     // 同事B发送消息
    mediator.colleagues[1].send(&mediator, "Hi, Colleague A!");
}

在上述代码中,我们首先定义了中介者接口Mediator,并实现了具体中介者ConcreteMediator。具体中介者维护了一个同事对象的集合,并实现了notify方法,用于通知其他同事对象。
然后,我们定义了同事接口Colleague,并实现了具体同事ConcreteColleagueA和ConcreteColleagueB。具体同事包含一个名称字段,并实现了send和receive方法,用于发送和接收消息。
在main函数中,我们创建了具体中介者对象mediator,以及具体同事对象colleague_a和colleague_b。然后,我们将同事对象注册到中介者对象中,并通过send方法发送消息。
通过中介者模式,我们可以将对象之间的交互逻辑集中在中介者对象中,降低了对象之间的耦合度,提高了系统的可维护性和灵活性。

关注我,学习Rust不迷路!!

你可能感兴趣的:(当Rust邂逅GOF,rust,rust,设计模式,中介者模式)