在C#中,中介者模式(Mediator Pattern)是一种行为型设计模式,它通过将对象之间的交互行为封装到一个中介者对象中,来解耦对象之间的复杂关系。中介者模式能够减少对象之间的直接依赖,提高系统的灵活性和可维护性。
中介者模式有以下几个关键角色:
Mediator(中介者):定义了对象之间的交互接口,可以是抽象类或接口。通常包括注册、转发消息等方法。
ConcreteMediator(具体中介者):实现了中介者接口,负责协调各个对象之间的交互关系。
Colleague(同事):定义了对象之间交互的接口,可以是抽象类或接口。通常包括发送和接收消息等方法。
ConcreteColleague(具体同事):实现了同事接口,负责实现具体的交互行为。
下面是一个示例,展示如何在C#中使用中介者模式来协调多个同事对象之间的交互:
namespace MediatorPattern_中介者模式
{
public interface IMediator
{
void Send(string message, Colleague colleague);
}
// ConcreteMediator
public class Chatroom : IMediator
{
private readonly List<Colleague> _colleagues = new List<Colleague>();
public void AddColleague(Colleague colleague)
{
_colleagues.Add(colleague);
}
public void Send(string message, Colleague colleague)
{
foreach (var c in _colleagues)
{
if (c != colleague)
{
c.Receive(message);
}
}
}
}
// Colleague
public abstract class Colleague
{
protected readonly IMediator _mediator;
public Colleague(IMediator mediator)
{
_mediator = mediator;
}
public abstract void Send(string message);
public abstract void Receive(string message);
}
// ConcreteColleague
public class User : Colleague
{
public User(IMediator mediator) : base(mediator)
{
}
public override void Send(string message)
{
_mediator.Send(message, this);
}
public override void Receive(string message)
{
Console.WriteLine("Received message: " + message);
}
}
}
namespace MediatorPattern_中介者模式
{
internal class Program
{
static void Main(string[] args)
{
Chatroom chatroom = new Chatroom();
User user1 = new User(chatroom);
User user2 = new User(chatroom);
User user3 = new User(chatroom);
chatroom.AddColleague(user1);
chatroom.AddColleague(user2);
chatroom.AddColleague(user3);
user1.Send("Hello, everyone!");
//输出结果
//Received message: Hello, everyone!
//Received message: Hello, everyone!
Console.Read();
}
}
}
在上述示例中,使用中介者模式实现了一个聊天室的功能。IMediator是中介者接口,定义了发送消息的方法Send。Chatroom是具体中介者,实现了中介者接口,负责协调各个User对象之间的交互。Colleague是同事接口,定义了发送和接收消息的方法。User是具体同事,实现了同事接口,通过中介者对象发送和接收消息。
在Client中,首先创建了一个聊天室(Chatroom)对象,并创建了多个用户(User)对象。然后将用户对象添加到聊天室中,并通过用户对象调用Send方法发送消息。聊天室在收到消息后会将消息转发给其他用户。
通过中介者模式,可以将复杂的对象之间的交互关系拆分为简单的一对多的关系,仅需关注中介者对象,而无需关注其他同事对象的具体实现细节。这样可以降低对象之间的耦合度,提高系统的可维护性和扩展性。中介者模式还可以隐藏对象之间的交互细节,使系统更加灵活和可复用。