Adapter pattern
easy 50 minThe Adapter pattern makes an existing class fit the interface that its client expects, without changing either of them.
Watch lesson4:39
Class, two-way, pluggable
The variants, with code, and the identity problem that wrappers bring.
The point: choose the form by what you must reach: override the inside, serve two sides, or avoid twenty tiny classes.
Class adapter
When you need the inside
class Scanner: def scan(self): return [self.read_line() for _ in range(2)] def read_line(self): return "raw"class TextSource: def lines(self): raise NotImplementedErrorclass ScannerAdapter(Scanner, TextSource): # is both def lines(self): return self.scan() def read_line(self): # replace one inner step return super().read_line().upper()source = ScannerAdapter()assert source.lines() == ["RAW", "RAW"]assert isinstance(source, TextSource) and isinstance(source, Scanner)print(source.lines())scan calls read_line on itself, so the override works. An object adapter could not reach this step from outside.The price: ScannerAdapter depends on the fact that scan uses read_line. If the next version of the library reads everything at once, the override is silently ignored. That is the fragile base class.
Two-way
Both sides may call it
class NewAlarm: def raise_alarm(self, level): self.last = levelclass OldAlarm: def ring(self, minutes): self.last = minutesclass TwoWayAlarm(NewAlarm, OldAlarm): """New code and old code both see an alarm of their own kind.""" def __init__(self, target): self._target = target def raise_alarm(self, level): # new words self._target.ring(level * 10) def ring(self, minutes): # old words self._target.ring(minutes)bell = OldAlarm()alarm = TwoWayAlarm(bell)alarm.raise_alarm(2)assert bell.last == 20alarm.ring(5)assert bell.last == 5print("both languages reach one bell")Pluggable
Twenty small differences
class FunctionPlayer: """One adapter class. The difference is passed in.""" def __init__(self, play): self._play = play def play(self, file_name, start_seconds=0): return self._play(file_name, start_seconds)class VlcEngine: def play_vlc(self, path, offset_ms): return (path, offset_ms)engine = VlcEngine()player = FunctionPlayer(lambda file, seconds: engine.play_vlc(file, seconds * 1000))assert player.play("a.vlc", 2) == ("a.vlc", 2000)print(player.play("a.vlc", 2))<lambda>.Which form?
| You need to | Form | Cost |
|---|---|---|
| Fit one interface, swap freely | Object adapter | One extra object |
| Override a step inside the adaptee | Class adapter | Bound to its inner calls |
| Serve old and new callers at once | Two-way adapter | Two contracts to keep |
| Many one-line differences | Pluggable | Anonymous code |
| Change the shape of one function | Function adapter | Nothing to inject |
| Give a type you do not own a new ability | Extension method, trait, singledispatch | Only where the language has it |
Identity
The wrapped object is another object
adapter == adaptee is false. Put one in a set and look for the other, and you will not find it. Register adapter.on_event as a listener and later remove a new adapter's on_event: nothing is removed, and the listener stays for ever.
Old code registers listeners by object and removes them by object. You wrap each listener in an adapter. How does removing work?
BreaksWrap again on removal
- How
bus.remove(ListenerAdapter(x))- Limit
- A new object, never equal. Listeners pile up, events arrive several times.
- Choose when
- Never.
WorksDefine equality over the adaptee
- How
- Two adapters of the same object are equal.
- Limit
- Must also define the hash, and
isstill differs. Surprising if two adapters have different settings. - Choose when
- Adapters without any settings of their own.
StrongRemember the adapter
- How
- A weak map from listener to adapter in the place that wraps. Same listener, same adapter.
- Limit
- One more map, weak so that it does not keep objects alive.
- Choose when
- Whenever wrapped objects are compared, removed or used as keys.