简体   繁体   中英

what's difference between a callback and observer pattern in java

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?

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 .

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.

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