Merge pull request #6590 from kwoyke/BAEL-2836

BAEL-2836 Mediator Pattern in Java
This commit is contained in:
Loredana Crusoveanu 2019-03-29 19:35:30 +02:00 committed by GitHub
commit 24ea44bdb5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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 MediatorIntegrationTest {
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());
}
}