Why does hardwiring a Subject class directly to a concrete Observer type create an Open/Closed Principle violation?
Once a Subject holds a direct reference to one specific listener type — a field of that exact class, set through the constructor — every new listener type that comes along forces the Subject's own source code open again: a new field, a new line inside whatever method pushes out notifications. That means code which was already written, tested, and shipped has to be modified every time the roster of interested parties grows, which is exactly what the Open/Closed Principle says should not happen. The fix is to have the Subject depend only on a shared Observer interface and hold a collection of that interface type, so new listeners plug in by implementing the interface and calling attach(), with zero changes to the Subject's existing, already-tested code.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response