Observer Pattern – Does ‘This’ in Observer Pattern Count as Composition?

compositiondesign-patternsobject-orientedobserver-pattern

In a classic implementation of the Observer design pattern, the subject has a list of references to all of it's observers, and each observer might have a reference to it's subject.

Is this considered composition? As far as I understand, composition means one object 'includes' in itself another object, in order to use functionality of that object. In the Observer pattern, the subject does include in itself references to it's observers, but it doesn't exactly use their functionality internally to do things outwardly. It keeps references so it can notify them.

On the other hand, the subject and observers maintain a relationship of HAS-A, which often characterizes composition (the subject has observers, the observers have a subject).

Is this considered a kind of composition?

Best Answer

Being notified as per the observer pattern is part of the functionality of the observing object. Insofar, this is an instance of composition.

It's just not a very large part of its functionality: typically, it means implementing one simple method to satisfy one very light-weight interface. Therefore, this is in no way a prototypical example for what people will think of when you mention "composition" to them, the coupling is much looser than it might be, etc. All this teaches us is that even seemingly clear-cut definitions are almost always a matter of degree in practice.