java设计模式学习笔记-17-中介者模式

中介者模式

public abstract class Mediator{
    public abstract void register(String colleagueName,Colleague colleague);
    
    public abstract void getMessage(int stateChange,String colleague);
    
    public void sendMessage();
}

public class ConcreteMediator extends Mediator{
    private HashMap<String,Colleague> colleagueMap;
    private HashMap<String,String> interMap;
    
    public ConcreteMediator(){
        colleagueMap = new HashMap<String,Colleague>();
        interMap = new HashMap<String,String>();
    }
    
    public void register(String colleagueName,Colleague colleague){
        colleagueMap.put(colleagueName,colleague);
        if(colleague instanceof Alarm){
            interMap.put("Alarm",colleagueName);
        }else if(colleague instanceof TV){
            interMap.put("TV",colleagueName);
        }
    }
    
    public void getMessage(int stateChange,String colleague){
        if(colleagueMap.get(ColleagueName) instanceof Alarm){
            if(stateChange == 0) {
                ((TV)(colleagueMap.get(interMap.get("TV")))).startTv();
            }else if(stateChange == 1){
                 ((TV)(colleagueMap.get(interMap.get("TV")))).stopTv();
            }
        }else if(colleagueMap.get(ColleagueName) instanceof TV){
            
        }
    }
}

puhblic abstract class Colleague{
    private Mediator mediator;
    public String name;
    
    public Colleague(Mediator mediator,String name){
        this.mediator = mediator;
        this.name = name;
    }
    
    public Mediator getMediator(){
        return mediator;
    }
    
    public bastract void sendMessage(int stateChange);
 
}

public class Alarm extends Colleague{
    public Alarm(Mediator mediator,String name){
        super(mediator,name);
        mediator.register(name,this);
    }
    
    public void sendAlarm(int stateChange){
        sendMessage(stateChange);
    }
    
    public void sendMessage(int stateChange){
        this.getMediator().getMessage(stateChange,name);
    }
}

public class TV extends Colleague{
    public Alarm(Mediator mediator,String name){
        super(mediator,name);
        mediator.register(name,this);
    }
    
    public void sendAlarm(int stateChange){
        sendMessage(stateChange);
    }
    
    public void sendMessage(int stateChange){
        this.getMediator().getMessage(stateChange,name);
    }
    
    public void startTv(){
        
    }
    
    public void stopTv(){
        
    } 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值