当前位置: 首页 > 图灵资讯 > 技术篇> 调解员

调解员

来源:图灵教育
时间:2024-09-18 15:21:06

调解员

在中介的帮助下,行为设计模式之一允许对象相互交流。 通过防止对象相互直接依赖,中介机构可以促进松散耦合。相反,他们使用中介机构相互交流。

让我们通过实现不同用户的聊天室来理解这一点

调解员

public interface chatmediator {
    public void sendmessage(user user, string message);
    public void adduser(user user);
}

public class chatroommediator implements chatmediator {
    private list<user> users;
    public chatroommediator(){
        this.users = new arraylist();
    }
    @override
    public void adduser(user u){
        users.add(u);
    }

    @override
    public void sendmessage(user u, string message){
        for(user user : users){
            if(user!=u){
                user.receive(message);
            }
        }
    }
}

</user>

用户

public class user {
    chatmediator mediator;
    private string name;

    public user(string n,chatmediator m){
        this.name = n;
        this.mediator = m;
    }
    public string getname(){
        return this.name;
    }

    public void send(string message){
        system.out.println(this.name+":sent:"+message);
        mediator.sendmessage(this,message);
    }
    public void receive(string message){
        system.out.println(this.name+":received:"+ message);
    }
}

主要

public class main {
    public static void main(string args[]){
        chatmediator mediator = new chatroommediator();
        user user1 = new user("prashant",mediator);
        user user2 = new user("sandeep", mediator);
        user user3 = new user("ajay", mediator);

        mediator.adduser(user3);
        mediator.adduser(user2);
        mediator.adduser(user1);

        user1.send("hi all");
        user2.send("hi prashant");
        user3.send("hi...");
    }
}

输出:

prashant:sent:Hi All
ajay:received:Hi All
sandeep:received:Hi All
sandeep:sent:Hi Prashant
ajay:received:Hi Prashant
prashant:received:Hi Prashant
ajay:sent:Hi...
sandeep:received:Hi...
prashant:received:Hi...

要点

  • 即使某些用户被删除或修改,也不会影响任何其他用户
  • mediator 它是所有用户之间的中间人

以上是调解人的详细内容。请关注图灵教育的其他相关文章!