I've seen some production code where Mediator pattern is used with Command pattern.
To be concret, I will provide an example, that I have seen in some course.
public class Mediator {
List<Light> lights = new ArrayList<>();
public void register(Light light) {
lights.add(light);
}
public void turnOnAllLights() {
lights.stream()
.filter(light -> !light.isOn())
.forEach(Light::toggle);
}
}
public class TurnAllLightsCommand implements Command{
private final Mediator mediator;
public TurnAllLightsCommand(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void execute() {
mediator.turnOnAllLights();
}
}
So, what benifits do we get from using Mediator here?
My point of view is the following:
- Commands are decoupled from each and do know nothing about colleagues, but it is achivebale without mediator (by just creating an invoker class, that takes Command for execution).
- In each command we get a new mediator object, and in command execution we just delegate the work to mediator.
- For each new command, that provides a specific operation, we should create a new Mediator implementation, or add new methods to an existing implementation.
- Being a client we can directly access both
turnOnAllLights.execute()
andmediator.turnOnAllLights()
. I find it a bit confusing.
Am I missing something?
Aucun commentaire:
Enregistrer un commentaire