Design patterns

patterns6AdapterPattern

Path
pkg8patterns/patterns6AdapterPattern.java
Package
pkg8patterns
Study order
6
Run
Single-file source launch
Command
java pkg8patterns/patterns6AdapterPattern.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg8patterns/patterns6AdapterPattern.java
1package pkg8patterns;2 3/*4 * Adapter (Structural)5 * --------------------6 * INTENT: convert the interface of a class into another interface clients expect.7 *         Lets incompatible classes work together.8 * UML: Target <- Adapter -> Adaptee (adapter implements Target, wraps Adaptee).9 * PROS: reuse existing/legacy code; separation of concerns.10 * CONS: extra indirection.11 * REAL-WORLD: Arrays.asList, InputStreamReader (bytes->chars), java.io adapters.12 */13public class patterns6AdapterPattern {14 15    // Target interface the client wants16    interface JsonLogger { void logJson(String json); }17 18    // Adaptee: an existing/legacy logger with a different API19    static class LegacyLogger {20        void writeLine(String text) { System.out.println("LEGACY> " + text); }21    }22 23    // Adapter makes LegacyLogger usable as a JsonLogger24    static class LoggerAdapter implements JsonLogger {25        private final LegacyLogger legacy;26        LoggerAdapter(LegacyLogger legacy) { this.legacy = legacy; }27        public void logJson(String json) { legacy.writeLine("json=" + json); }28    }29 30    public static void main(String[] args) {31        JsonLogger logger = new LoggerAdapter(new LegacyLogger());32        logger.logJson("{\"event\":\"login\"}");33    }34}