D
D
Davidaa_WoW2022-03-04 12:32:18
Java
Davidaa_WoW, 2022-03-04 12:32:18

Why does a java.lang.IllegalMonitorStateException occur when building the mediator pattern?

I'm trying to create a mediator pattern
. There is a Mediator interface:

package Eighth.mediator;

public interface Mediator {
    void notify(Components components);
}


There is a class that implements it:

package Eighth.mediator;

public class ConcreteMediator implements Mediator{
    @Override
    public void notify(Components components) {
        System.out.println("User pressed " + components.getName());
    }
}


There is a component interface:

package Eighth.mediator;

public interface Components {
    String getName();
    void onPress();
}


There are several classes of components that are similar to each other, for example:
package Eighth.mediator;

public class Button implements Components{
    public Mediator mediator;

    private String name;

    public Button(String name) {
        this.name = name;
        mediator = new ConcreteMediator();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void onPress(){
        mediator.notify();
    }
}


I'm trying to run it all in Main:

package Eighth.mediator;

public class Main {
    public static void main(String[] args) {
        Components button1 = new Button("Button1");
        Components button2 = new Button("Button2");
        Components checkbox1 = new Checkbox("Checkbox1");
        Components radioButton1 = new RadioButton("Radiobutton1");
        Components checkbox2 = new Checkbox("Checkbox2");
        button1.onPress();
        button2.onPress();

    }
}


The same error java.lang.IllegalMonitorStateException pops up when executing the onPress method.
What's the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2022-03-04
@Davidaa_WoW

Because you are calling the .notify() method from the Object and not from the Mediator
like this:

public void onPress(){
        mediator.notify();
    }

you have a method like this: void notify(Components components);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question