简体   繁体   中英

Add another method to every implementation of my Interface in all implementations

I have an interface:

public interface InterfaceListener {
    void eventEnd();
}

Some methods receives this InterfaceListener as a parameter and every one of course implement it on his own way. For example:

myObject.callMethod(false,InterfaceListener() {
    @Override
    public void eventEnd() {
        //do some extra code
    }
});

Now I want to add some changes, to insure that every implementation in eventEnd() will be called only after it's passed another method - callMyExtraMethod() that common to all the calls, something like that:

myObject.callMethod(false,InterfaceListener() {
    @Override
    public void eventEnd() {
        if (callMyExtraMethod()) {
            //do some extra code
        }
    }
});

Any ideas how can I add it to the logic without passing on every implementation and adding manually that same check to all?

Rename eventEnd to eventEndImpl in IDE. Then add default method:

public interface InterfaceListener {
    default void eventEnd() {
        if (callMyExtraMethod()) {
            eventEndImpl();
        }
    }

    void eventEndImpl();
    // Uncomment, if this method must belong to the same class. 
    // bool callMyExtraMethod();
}

If you are using Java 7, one way to achieve this -

Create an AbstractListener class with abstract methods
eventEnd and callMyExtraMethod and a template method templateMethod

public abstract class AbstractListener {

   public abstract void eventEnd();
   public abstract boolean callMyExtraMethod();

   public void templateMethod(){
    if(callMyExtraMethod()){
        eventEnd();
    }
  }
}

Now you can create the Anonymous classes and call the templateMethod() . This will ensure the callMyExtraMethod() check before invoking eventEnd()

AbstractListener listener = new AbstractListener() {

        @Override
        public void eventEnd() {
            // your implementation
        }

        @Override
        public boolean callMyExtraMethod() {
            //System.out.println("I am callMyExtraMethod");
            return true;
        }
    };

    listener.templateMethod();

Hope this helps.

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