1

In Java the observer pattern is implemented with at least one interface (often ending in Listener or Observer). Such interfaces can be placed nested inside the class or be separate, for example:

public class FooService extends RunnableService {
    // Nested interface
    public interface Listener {
        // ...
    }

    private Collection<Listener> listeners;

    // ...
}

// Separate interface
public interface FooServiceListener {
    // ...
}

public class FooService extends RunnableService {
    private Collection<FooServiceListener> listeners

    // ...
}

The name of the nested interface is only one character longer and does not have to be prefixed with the name of the class to avoid simple name conflicts.

Are there other arguments for or against either one of both variants (besides personal preference)?

1

If you embed the interface within the class, you are tightly coupling the interface to an implementation. This pre-supposes that this implementation will be the only one for that interface, which is a bad assumption to make. In fact, with this thinking, why even have the interface in the first place.

Such coupling of the interface to the implementation is example of the entourage anti-pattern in action: using the interface forces you to bring along an implementation with it, even if not needed.

So the conclusion is: keep the two separate. They are separate entities and should not be coupled.

  • Why do you think the interface is tightly coupled and why should it be separate from the class (e.g. an error listener)? You can also nest multiple interfaces for multiple observable aspects of the class. – user3998276 Nov 4 '15 at 14:04
  • 1
    @DavidArno I think you're missing the point of the question. The interface would be declared as a nested class of its consumer, not its implementers. See, for example, many such interfaces in the Android API, eg ListView.OnItemClickListener. – Jules Nov 5 '15 at 0:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.