5

Is there an existing named software design pattern similar to Observer, but for the case where only a single observer is supported rather than a collection of observers.

I find that I use this pattern fairly often, particularly in cases where an adapter has the ability to provide fan-out (notify multiple observers) on behalf of the object with the simpler call-back behavior. I would like to be able to use a name for what I'm doing that will make the most sense to others.

6
  • AFAIK "fan-out" is not a technical term of the kind that you can find explained in software engineering books. Would you like to explain it?
    – Mike Nakis
    Commented Jan 6, 2016 at 6:14
  • @MikeNakis Thanks for your observation. I have edited the question & hopefully clarified my meaning. Commented Jan 6, 2016 at 6:17
  • 2
    Isn't this simply a "callback" (or maybe something like "callback object" since it seems that different functions might be called)? Commented Jan 6, 2016 at 7:49
  • 1
    Lonely Observer
    – joshp
    Commented Jan 6, 2016 at 8:10
  • 1
    …or maybe Lonesome Observer. :) Commented Jan 6, 2016 at 23:04

1 Answer 1

5

There are two cases:

  1. The observer is specified (passed or otherwise injected) at construction time.

  2. The observer is registered and unregistered after construction time.

If the observer is specified at construction time, it could be thought of as a peer.

If the observer is registered and unregistered after construction time, then the fact that only one observer is supported is best considered to be an implementation detail, and not exposed in any way, shape, or form. Pretend that you support multiple observers, assert that only one ever gets registered. This way, if you ever decide to allow multiple observers in the future, nothing but the implementation needs to change.

2
  • My case is somewhere in between your #1 and #2. Registration happens once, after construction, but within the "main section". In any case, I like your suggestion of simply calling it Observer, and it happens to have restrictions. Commented Jan 6, 2016 at 6:23
  • If a class only supports one observer, then the result of attempting to add another should be specified. And once it's specified, it should never be changed. The fact that only one observer is supported is often exposed via self-documenting method names, e.g., setFooListener vs. addFooListener. If a class only supports one observer now, give it a set... method. If the design changes, give it an add... method and deprecate the set... version. Commented Jan 8, 2016 at 3:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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