BAEL-2836 Mediator Pattern in Java

This commit is contained in:
Krzysiek 2019-03-25 21:15:34 +01:00
parent fda8a29eb6
commit 52587443de
5 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,13 @@
package com.baeldung.mediator;
public class Button {
private Mediator mediator;
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
public void press() {
this.mediator.press();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.mediator;
public class Fan {
private Mediator mediator;
private boolean isOn = false;
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
public boolean isOn() {
return isOn;
}
public void turnOn() {
this.mediator.start();
isOn = true;
}
public void turnOff() {
isOn = false;
this.mediator.stop();
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.mediator;
public class Mediator {
private Button button;
private Fan fan;
private PowerSupplier powerSupplier;
public void setButton(Button button) {
this.button = button;
this.button.setMediator(this);
}
public void setFan(Fan fan) {
this.fan = fan;
this.fan.setMediator(this);
}
public void setPowerSupplier(PowerSupplier powerSupplier) {
this.powerSupplier = powerSupplier;
}
public void press() {
if (fan.isOn()) {
fan.turnOff();
} else {
fan.turnOn();
}
}
public void start() {
powerSupplier.turnOn();
}
public void stop() {
powerSupplier.turnOff();
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.mediator;
public class PowerSupplier {
public void turnOn() {
// implementation
}
public void turnOff() {
// implementation
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.mediator;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ButtonTest {
private Button button;
private Fan fan;
@Before
public void setUp() {
this.button = new Button();
this.fan = new Fan();
PowerSupplier powerSupplier = new PowerSupplier();
Mediator mediator = new Mediator();
mediator.setButton(this.button);
mediator.setFan(fan);
mediator.setPowerSupplier(powerSupplier);
}
@Test
public void givenTurnedOffFan_whenPressingButtonTwice_fanShouldTurnOnAndOff() {
assertFalse(fan.isOn());
button.press();
assertTrue(fan.isOn());
button.press();
assertFalse(fan.isOn());
}
}