public interface Mediator {
void change(Module module);
}
public class VolMediator implements Mediator {
private Speaker speaker;
private VolButton volButton;
@Override
public void change(Module module) {
if (volButton == module) {
if (volButton.status==0){
speaker.louder(volButton.vol);
System.out.println("音量加"+volButton.vol);
}else{
speaker.lighter(volButton.vol);
System.out.println("音量减"+volButton.vol);
}
}
}
public void setSpeaker(Speaker speaker) {
this.speaker = speaker;
}
public void setVolButton(VolButton volButton) {
this.volButton = volButton;
}
}
public abstract class Module {
protected Mediator mediator;
public Module(Mediator mediator){
this.mediator=mediator;
}
}
public class Speaker extends Module{
public Speaker(Mediator mediator){
super(mediator);
}
public void louder(int i){
System.out.println("音量增加" + i);
}
public void lighter(int i){
System.out.println("音量减少"+i);
}
}
public class VolButton extends Module {
public int status=0;
public int vol=0;
public VolButton(Mediator mediator){
super(mediator);
}
public void up(int i){
status=0;
vol=i;
mediator.change(this);
}
public void down(int i){
status=1;
vol=i;
mediator.change(this);
}
}
public class App {
public static void main(String[] args) {
VolMediator mediator=new VolMediator();
Speaker speaker=new Speaker(mediator);
VolButton volButton=new VolButton(mediator);
mediator.setSpeaker(speaker);
mediator.setVolButton(volButton);
volButton.up(10);
volButton.down(10);
}
}