Lesson 3 of 6
Structural Patterns - Decorator & Adapter
Structural patterns define how classes and objects are composed. Decorator adds behaviour without subclassing (wraps an object). Adapter makes incompatible interfaces work together (wraps an existing class with a new interface).
Decorator & Adapter Patterns
// ─── Decorator ───────────────────────────────────────────────
// Add responsibilities to objects at runtime without modifying the class.
interface BookRepository {
Optional<Book> findByIsbn(String isbn);
void save(Book book);
}
// Base implementation
class JdbcBookRepository implements BookRepository {
public Optional<Book> findByIsbn(String isbn) { /* SQL */ return Optional.empty(); }
public void save(Book book) { /* SQL */ }
}
// Decorator 1: Logging - wraps ANY BookRepository, adds logging
class LoggingBookRepository implements BookRepository {
private final BookRepository delegate;
private static final Logger LOG = Logger.getLogger(LoggingBookRepository.class.getName());
LoggingBookRepository(BookRepository delegate) { this.delegate = delegate; }
public Optional<Book> findByIsbn(String isbn) {
LOG.fine("findByIsbn: " + isbn);
long start = System.currentTimeMillis();
Optional<Book> result = delegate.findByIsbn(isbn);
LOG.fine("findByIsbn done in " + (System.currentTimeMillis() - start) + "ms: " + result.isPresent());
return result;
}
public void save(Book book) {
LOG.info("Saving book: " + book.getIsbn());
delegate.save(book);
}
}
// Decorator 2: Caching - wraps any BookRepository, adds cache layer
class CachingBookRepository implements BookRepository {
private final BookRepository delegate;
private final Map<String, Book> cache = new ConcurrentHashMap<>();
CachingBookRepository(BookRepository delegate) { this.delegate = delegate; }
public Optional<Book> findByIsbn(String isbn) {
Book cached = cache.get(isbn);
if (cached != null) return Optional.of(cached);
Optional<Book> found = delegate.findByIsbn(isbn);
found.ifPresent(b -> cache.put(isbn, b));
return found;
}
public void save(Book book) {
delegate.save(book);
cache.put(book.getIsbn(), book); // update cache on write
}
}
// Stack decorators dynamically:
BookRepository repo = new CachingBookRepository(
new LoggingBookRepository(
new JdbcBookRepository()));
// Call flows: CachingRepo → LoggingRepo → JdbcRepo
// ─── Adapter ─────────────────────────────────────────────────
// Make incompatible interfaces work together.
// External library - incompatible interface we can't change
class LegacyLibrarySystem {
public String[] getBookList() { return new String[]{"001:Clean Code:39.99"}; }
public boolean checkoutByCode(String code) { return true; }
public void returnByCode(String code) { }
}
// Our Book interface
interface BookSource { List<Book> findAll(); boolean checkout(String isbn); }
// Adapter - translates LegacyLibrarySystem to BookSource
class LegacySystemAdapter implements BookSource {
private final LegacyLibrarySystem legacy;
LegacySystemAdapter(LegacyLibrarySystem legacy) { this.legacy = legacy; }
public List<Book> findAll() {
return Arrays.stream(legacy.getBookList())
.map(this::parseLine)
.collect(Collectors.toList());
}
public boolean checkout(String isbn) { return legacy.checkoutByCode(isbn); }
private Book parseLine(String line) {
String[] parts = line.split(":");
return new Book(parts[0], parts[1], "Unknown", Double.parseDouble(parts[2]));
}
}Quick Quiz
Tip
Tip
Practice Structural Patterns Decorator Adapter in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Structural Patterns - Decorator & Adapter
Practice Task
Note
Practice Task - (1) Write a working example of Structural Patterns Decorator Adapter from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Structural Patterns Decorator Adapter is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?