首页 > 解决方案 > Anti-pattern name for firing events on an object member supplied at instantiation?

问题描述

An object requires it be instantiated with an object upon which it can call a method to register than an event has occurred — rather than the instantiating code listening for events.

Is this an anti-pattern? If so, does it have a name?

Is there a reason to code this way?

标签: design-patternsanti-patterns

解决方案


Passing an object-to-be-called into a constructor is usually used for the "constructor injection" type of dependency injection. See: https://en.wikipedia.org/wiki/Dependency_injection#Constructor_injection

When used in that way it's an excellent pattern...

But if the object being passed in is really an event listener, then it becomes a bad idea. Injecting an event listener is not "dependency injection", because an object doesn't depend on its event listeners, and so it shouldn't require any in its constructor. It would also be very bad form to restrict an event-generating object such that it could have only one listener.


推荐阅读