【设计模式】中介者模式

使用频率:★★★☆☆

一、什么是中介者模式

对象之间通过中介者对象进行交互,而不是直接交互;

二、补充说明

对紧密关联的各个对象解耦;

典型例子:QQ群,聊天室;

三、角色

抽象中介者

具体中介者

抽象对象

具体对象

四、例子,JAVA实现

例子说明,一个网络聊天室

抽象中介者

package com.pichen.dp.behavioralpattern.mediator;

import java.util.ArrayList;
import java.util.List;

public abstract class Mediator {

    protected List<User> userList;
    public Mediator() {
        userList = new ArrayList<User>();
    }
    public void addUser(User user){
        user.setMediator(this);
        this.userList.add(user);
    }
    
    public abstract void operation(User user, String msg);
}

具体中介者

package com.pichen.dp.behavioralpattern.mediator;
public class ChatRoomMediator extends Mediator {

    @Override
    public void operation(User user, String msg) {
        System.out.println(user.getName() + "send a msg : " + msg);
        for(User userTmp : this.userList){
            userTmp.getMessage(msg);
        }
    }
}

抽象对象

package com.pichen.dp.behavioralpattern.mediator;

public abstract class User {
    protected Mediator mediator;
    
    protected String name;
    
    public User(String name) {
        this.name = name;
    }
    
    protected void setMediator(Mediator mediator){
        this.mediator = mediator;
    }
    protected abstract void sendMessage(String msg);

    protected abstract void getMessage(String msg);
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

具体对象

package com.pichen.dp.behavioralpattern.mediator;
public class CommonUser extends User{

    public CommonUser(String name) {
        super(name);
    }
    @Override
    protected void sendMessage(String msg) {
        this.mediator.operation(this, msg);
    }

    @Override
    protected void getMessage(String msg) {
        System.out.println(this.getName() +  " get msg:"+msg);
    }

    
}
package com.pichen.dp.behavioralpattern.mediator;
public class VIPUser extends User{
    public VIPUser(String name) {
        super(name);
    }

    @Override
    protected void sendMessage(String msg) {
        this.mediator.operation(this, msg);
    }

    @Override
    protected void getMessage(String msg) {
        System.out.println(this.getName() + " get msg:"+msg);
    }

}

客户端

package com.pichen.dp.behavioralpattern.mediator;
public class Main {

    public static void main(String[] args) {
        CommonUser user1 = new CommonUser("小王");
        CommonUser user2 = new CommonUser("小陈");
        VIPUser vipUser = new VIPUser("小张");
        
        Mediator chatRoom = new ChatRoomMediator();
        chatRoom.addUser(user1);
        chatRoom.addUser(user2);
        chatRoom.addUser(vipUser);

        user2.sendMessage("hello everybody~");
        
    }
}

执行结果

小陈send a msg : hello everybody~
小王 get msg:hello everybody~
小陈 get msg:hello everybody~
小张 get msg:hello everybody~

 

posted @ 2016-02-27 00:02  风一样的码农  阅读(...)  评论(... 编辑 收藏