Search code examples
javacallbackobserver-pattern

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?


Solution

  • 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.