Namgyu Ho
Namgyu Ho

Reputation: 372

Abstract Method vs Listener

I'm making a button class that handles input and drawing by itself; the only thing that needs to be defined is the location and what happens when the button is pressed.

In this situation, would it be better to have a ButtonPressListener interface and have it as a parameter in Button's constructor, or should the Button be abstract with the abstract method pressed()?

The resulting initiation code for Button would be like the following:

new Button(x,y,new ButtonPressListener(){
    @Override
    protected void pressed(){
        // code
    }
});

or

new Button(x,y){
    @Override
    protected void pressed(){
        // code
    }
};

Also, in other similar situations, what should be considered when choosing between the two approaches?

Thanks.

Upvotes: 4

Views: 493

Answers (2)

slartidan
slartidan

Reputation: 21576

I prefer the listener.

Resons:

  • The listener will give you more flexability, when using java8 lambdas.
  • You can write one class that listens to several buttons
  • You can write one class that listens to a button and inherits some other class

By the way: You should consider using a setter, rather then a parameter of the constructor. This will allow to create buttons without listeners - or define more than one listener. Also parameters are a little bit harder to read then setter, as parameters cannot have names in java.

Upvotes: 3

Stefan Bormann
Stefan Bormann

Reputation: 693

If you are trying to learn from this project, you might as well do both at the same time and find out what works better for you. Wenn you found out, refactor and throw out the less liked option.

Make a default implementation of Button.pressed() that calls the function of your listener implementation if set. Supply two constructors, one that sets the listener and one that does not.

Of course that is not an option is others shall use this API.

Upvotes: 1

Related Questions