首页 > 其他 > 详细

中介者模式

时间:2020-02-28 21:30:53      阅读:45      评论:0      收藏:0      [点我收藏+]

使用一个中介管理相关对象之间的交互

类图

技术分享图片

 

示例(中介者模式来模拟用户之间的聊天)

public abstract class User {
    private IChatRoom chartroom;
    private String userId;
    private String userName;

    public User(IChatRoom room, String userId, String userName) {
        this.chartroom = room;//用户选择聊天室
        this.userId = userId;
        this.userName = userName;
    }

    public abstract void sendMessage(String msg, String userId);

    public abstract void receiveMessage(String msg);

    public String getUserId() {
        return userId;
    }

    public String getUserName() {
        return userName;
    }

    public IChatRoom getChartroom() {
        return chartroom;
    }
}

public class ChartUser extends User {
    public ChartUser(IChatRoom room, String userId, String userName) {
        super(room, userId, userName);
    }

    @Override
    public void sendMessage(String msg, String userId) {
        System.out.println(this.getUserName()+" send message:"+msg);
        this.getChartroom().sendMessage(msg,userId);
    }

    @Override
    public void receiveMessage(String msg) {
        System.out.println(this.getUserName()+" receive message:"+msg);
    }
}

public interface IChatRoom {
    void sendMessage(String msg,String userId);
    void addUser(User user);
}

public class ChartUser extends User {
    public ChartUser(IChatRoom room, String userId, String userName) {
        super(room, userId, userName);
    }

    @Override
    public void sendMessage(String msg, String userId) {
        System.out.println(this.getUserName()+" send message:"+msg);
        this.getChartroom().sendMessage(msg,userId);
    }

    @Override
    public void receiveMessage(String msg) {
        System.out.println(this.getUserName()+" receive message:"+msg);
    }
}

//测试
public class Client {
    public static void main(String[] args){
        IChatRoom chatRoom = new ChatRoom();
        //初始化用户
        User userA = new ChartUser(chatRoom,"A","USERA");
        User userB = new ChartUser(chatRoom,"B","USERB");
        //用户注册到中介
        chatRoom.addUser(userA);
        chatRoom.addUser(userB);
        //模拟发送消息
        userA.sendMessage("Hello","B");
        System.out.println("********************");
        userB.sendMessage("Hello","A");
    }
}

运行结果

 

 技术分享图片

中介者模式

原文:https://www.cnblogs.com/camcay/p/12379936.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!