How can we create a
TemperatureAdapter class that is not coupled to a
specific target class? We need some way of telling the adapter how to
forward an event to the target. In the earlier examples, the
TemperatureAdapter class had knowledge about the
methods available in the
Thermometer class. But
this is no good, because we want to decouple the adapter from the
target. Normally we would define an interface for the target object
to implement, but if we did, we would have the same problem we had
before the adapter was introduced. The proposed interface can be
implemented only once, so again we would have no way of knowing which
adapter was forwarding the event to us.
Let’s take a closer look at what we’re trying to do here. We’re actually trying to create a mapping from the event forwarded by an instance of a given adapter to a method on the listening object, without forcing the listener to declare that it implements any particular Java interface. We want multiple instances of a specific adapter to forward their events to different methods on the same target, as shown in Figure 3.3.
Figure 3-3. Adapters for events from several sources
In order to do this in a generic way, we need a mechanism for telling the adapter at run-time which method to invoke when it forwards an event. If we were programming in C++, we could use function pointers to accomplish this. The adapter ...