简体   繁体   中英

Mediator Design Pattern: Why do classes have to inform mediator of their behaviours?

In the following class:

public class Ignition {
    private EngineManagementSystem mediator;
    private boolean on;

        public Ignition(EngineManagementSystem mediator) {
        this.mediator = mediator;
        on = false;
        mediator.registerIgnition(this);
    }

    public void start() {
        on = true;
        mediator.ignitionTurnedOn();
        System.out.println("Ignition turned on");
   }

    public void stop() {
        on = false;
        mediator.ignitionTurnedOff();
        System.out.println("Ignition turned off");
    }
    public boolean isOn() {
        return on;
    }} 

I am unsure of the reason for these lines of code, eg:

mediator.ignitionTurnedOn();

Why does this class need to invoke this method to inform the mediator that the ignition is on? would this mean that the method is invoked twice? Once by this method and then within the mediator itself?

The purpose of the mediator is to relay information between colleagues. You only have to inform the mediator of things that other colleagues in your system need to know about.

I would venture that in this system, there is perhaps another class perhaps called Engine which has a start() method also registered with the mediator.

When the Ignition start method calls mediator.ignitionTurnedOn() , most likely, the mediator then calls something like getEngine().start() from inside its ignitionTurnedOn() method.

Probably nothing is invoked twice here.

The purpose of the mediator is to provide highly cohesive services that allow to decouple the elements of the system. In terms of a car, the Ignition system would not need to know the details of what happens, eg, a Choke is opened, a Starter is invoked, etc. as these details can change depending on the type of Engine system.

So, here's what happens likely:

plantUML图片

To know for sure, you'd have to see how :Ignition is being called and what Mediator.ignitionTurnedOn() actually does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM