3

I was going through the following link in stack over flow

How do I perform a JAVA callback between classes?

In the particular question answer 18 refers to callbacks and answer 9 refers to the observer pattern.

I am unable to distinguish the difference between both.

Can anyone please explain where these two approaches differ?

Community
  • 1
  • 1
jana
  • 119
  • 9

2 Answers2

1

A callback is basically a piece of code that your provide for a class and gets called by it at a certain point. Ex:

serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
        @Override
        public void execute(Socket socket) {
            // do something with your socket here
        }
});

The observer's pattern is a design pattern that is based on callbacks. You can find more details about it here http://en.wikipedia.org/wiki/Observer_pattern.

DSF
  • 804
  • 7
  • 15
1

Question should instead be framed as how observer pattern helps in achieving callback functionality.

I wanted to give clear example which explains callbacks in a way how listeners (observers) works - following approach is greatly adopted by android library.

class RemoteClass {

    private OnChangeListener mOnChangeListener;

    void makeSomeChanges() {
        /*
        .. do something here and call callback
        */
        mOnChangeListener.onChanged(this, 1);
    }

    public void setOnChangeListener(OnChangeListener listener) {
        mOnChangeListener = listener;
    }

    public interface OnChangeListener {
        public void onChanged(RemoteClass remoteClass, int test);
    }
}

There is a class built my someone, which goes by name RemoteClass and tells your class to reference the callback by passing implementation of OnChangeListener interface to setOnChangeListener method.

class Test {

    public static void main(String[] args) {    
        RemoteClass obj = new RemoteClass();
        obj.setOnChangeListener(demoChanged);
        obj.makeSomeChanges();
    }

    private static RemoteClass.OnChangeListener demoChanged = new RemoteClass.OnChangeListener() {
        @Override
        public void onChanged(RemoteClass remoteClass, int incoming) {
            switch (incoming) {
                case 1:
                    System.out.println("I will take appropriate action!");
                    break;
                default:
                    break;
            }
        }
    };
}

Now your class has finished doing its task and RemoteClass does its work and upon calling makeSomeChanges whenever necessary results in onChanged method execution using mOnChangeListener reference.

VinKrish
  • 357
  • 1
  • 5
  • 17