对象之间直接通信的话,比较乱套,所以找个中介来帮着传话。

用聊天室的例子再合适不过了。

public interface ChatRoom
{
    void Register(User user);
    void SendMessage(User fromUser, string message);
}

public class ConcreteChatRoom : ChatRoom
{
    private Dictionary<string, User> users = new Dictionary<string, User>();

    public void Register(User user)
    {
        users[user.Name] = user;
    }

    public void SendMessage(User fromUser, string message)
    {
        foreach (var user in users.Values)
        {
            if (user != fromUser)
            {
                user.ReceiveMessage(fromUser.Name, message);
            }
        }
    }
}

public abstract class User
{
    protected ChatRoom chatRoom;
    public string Name { get; }

    public User(string name, ChatRoom chatRoom)
    {
        Name = name;
        this.chatRoom = chatRoom;
    }

    public abstract void Send(string message);
    public abstract void ReceiveMessage(string fromUser, string message);
}


public class ConcreteUser : User
{
    public ConcreteUser(string name, ChatRoom chatRoom) : base(name, chatRoom)
    {
    }

    public override void Send(string message)
    {
        chatRoom.SendMessage(this, message);
    }

    public override void ReceiveMessage(string fromUser, string message)
    {
        Console.WriteLine($"{Name} received a message from {fromUser}: {message}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        ChatRoom chatRoom = new ConcreteChatRoom();

        User user1 = new ConcreteUser("User1", chatRoom);
        User user2 = new ConcreteUser("User2", chatRoom);
        User user3 = new ConcreteUser("User3", chatRoom);

        chatRoom.Register(user1);
        chatRoom.Register(user2);
        chatRoom.Register(user3);

        user1.Send("Hello, everyone!");
    }
}