Dishonered
Dishonered

Reputation: 8841

Java - What will be proper design/design pattern for this case?

I have to listen to an event from an event emitting class ; for Example click. Current i have class which handles it the events from the event emitting class like this.

someclass.clickedOnItem1()
someclass.clickedOnItem2()

where someclass is

class Someclass {
   //functions clickedOnItem1() and clickedOnItem2()
}

note that Someclass does not implement an interface. My problem is that i want only certain subclasses of Someclass to have this behavior and have the capacity to override the behavior but also have some default behavior in class Someclass. The default behaviour of Someclass depends on specific behavior which is only available in certain subclasses. I was considering composition where each subclass can provide a custom implemntation of an interface which handles click events. I am currently looking for advice on the best possible design pattern which can address this issue.

Upvotes: 1

Views: 73

Answers (1)

ernest_k
ernest_k

Reputation: 45319

This won't answer the what design pattern question, but just considering OOP concepts: you can use abstraction in SomeClass, and:

  • Declare abstract methods to obtain specifics from concrete classes
  • Make the entry-point (event handling) methods final in SomeClass to freeze decision making based on subclass-supplied specific configuration. This is important to prevent subclasses from skipping logic you want to control in the superclass.

SomeClass can look like this:

abstract class Someclass {
    final void clickedOnItem1(){
        if(this.getConcreteOption()) {
             //do if concreteOption
        }

        this.performClickOnItem1Action();
    }

    void performClickOnItem1Action() {

    }

    abstract boolean getConcreteOption();
}

This will force subclasses to supply specific config, keeping control of the flow in the superclass, while at the same time allowing concrete classes to override behavior.

Subclasses can look like:

class SomeclassA {
    void performClickOnItem1Action() {
        //overriding this...
    }

    boolean getConcreteOption() {
        return true;//or false
    }
}

class SomeclassB {
    boolean getConcreteOption() {
        return true;//or false
    }
}

Upvotes: 2

Related Questions