dimanche 10 janvier 2016

Is that a right way of using interface callback?

I read this and this and found out that in class B I need to save a reference to class A and when something happens in class B we execute a method defined by interface that class ``A` implements. Well somehow I understood it. I use interfaces in a bit different way to call a callback:

interface IHelper {
    void onActionDone ();
    void onActionFailed ();
}

public class Helper implements IHelper {

    public Helper (Param param) {
        // here we do what Helper class intended to do
        // ...
        // now call the any of callbacks
        if(everything == OK) {
            onActionDone();
        } else {
            onActionFailed();
        }
    }

    @Override
    public void onActionDone() {}

    @Override
    public void onActionFailed() {}
}

public class MainClass () {
    new Helper(message) {
        public void onActionDone () {
            // here we can do anything we want after Helper will done its functions
        }
        public void onActionFailed () {
            // or not done
        }
    }
}

I find this way more readable and easy to understand but not sure this is not a bad practice. So may I feel free to go this way further?

Aucun commentaire:

Enregistrer un commentaire