Instructor: Stefan Mitsch
SlackNotifier
Adapter converts an interface of a class into another interface
Problem illustration: want to use a different library with incompatible interface
How to use library without changing existing client code?
Problem
Intent
Structure
The Client contains the existing business logic of the program
Client
The Adaptee provides a useful service (third-party or legacy) that doesn't work directly with the Client because of interface differences
Adaptee
The Target interfaces defines the interface expected by the Client
Target
The Adapter implements the Target interface by forwarding to the Service
Adapter
Service
The client code is decoupled from the concrete adaptee and from the adapter; thanks to the Target interface, new adapter implementations can be added without breaking the Client
Power adapters for different countries Image from "Dive into Design Patterns"
// client uses a target service/library public class Character { private int strength; private CharacterStore s; public void save() { s.save(this); } /* ... */ } // target public abstract class CharacterStore { public abstract void save(Character c); } // incompatible library public class JSONStore { public void persist(JSON data) { /*...*/ } } // adapter public class JSONCharacterStore extends CharacterStore { private JSONStore s; public void save(Character c) { s.persist(toJSON(c)); } private JSON toJSON(Character c) { // convert } }
Code Smell: A class adapts multiple versions of a library
Before: Conditional code
Decorator