The Adapter Pattern
1 The Adapter Pattern

The Adapter Pattern

CS 3500, Fall 2023

The java.lang.Appendable interface

For objects to which characters can be appended or written:

  * An object to which {@code char} sequences and values can be appended.
public interface Appendable {
   * Appends the specified character to this {@link Appendable}.
  Appendable append(char c);

   * Appends the specified character sequence to this
   * {@link Appendable}.
  default Appendable append(CharSequence cst) {

Examples: PrintStream, FileWriter, LogStream, ...

Generifying output code

Works only with PrintStreams:

void dumpHashtableStats(PrintStream out) {

Works with any Appendable (including PrintStreams):

void dumpHashtableStats(Appendable out) {
StringAccumulator acc = new DoublingStreamAccumulator();

ht.dumpHashtableStats(acc);       // Doesn't work!

Recall our StringAccumulator interface

public interface StringAccumulator {
  void add(char c);
  String stringValue();

Suppose we can't change dumpHashTableStats and StringAccumulator.

Can we still use a StringAccumulator with dumpHashtableStats?

An adapter!

A StringAccumulator to Appendable adapter

public final class StringAccumulatorToAppendableAdapter
  implements Appendable
  private final StringAccumulator adaptee;

  StringAccumulatorToAppendableAdapter(StringAccumulator acc)
    adaptee = acc;

  public Appendable append(char c) {
    return this;

The object adapter pattern

The class adapter pattern