UNC COMP 301 - F26/Lec 12 - Adapter Design Pattern; Composition over Inheritance; Decorator DP
Overview
Muhammad Sayeed Ghani explains two structural design patterns and the design principle behind them: Adapter translates an incompatible API into the interface a client expects, while Decorator adds or modifies behavior through composition rather than a growing inheritance hierarchy. Media-player, dog, window, and price-tag examples show how delegation works, why feature combinations can cause class explosion, how decorators can be chained, and where Java’s I/O classes use the pattern.
Key takeaways
- An Adapter preserves both sides of an integration boundary: it implements the interface the client expects, wraps the incompatible adaptee, and delegates calls to the adaptee’s existing methods.
- When features are independent, subclass counts multiply: three binary window features require eight combinations, while a single class with runtime state or composable decorators avoids that subclass explosion.
- A Decorator must implement the wrapped component’s interface, hold a reference to a component of that interface, and delegate unchanged operations while modifying only the behavior it adds.
- Decorators can be chained, so two $20 discounts around a $100 price tag produce $60 through successive wrapper calls rather than copied price state.
- Java’s I/O wrappers illustrate practical decoration: BufferedInputStream and PushbackInputStream add behavior around sources such as files or piped program output.
- Decorator flexibility has costs: application order and compatibility may matter, and composition does not grant direct access to private or protected fields in the wrapped object.
Chapters
- Structural patterns organize classes and objects into larger structures, unlike behavioral patterns such as Iterator or creational patterns.
- The Gang of Four defines Adapter as converting a class interface into one expected by a client, allowing otherwise incompatible classes to work together.
- The lecture first covers Adapter, then returns to composition over inheritance and Decorator.
- The client expects a MediaPlayer interface with a play(fileName) method.
- A legacy VLC player instead exposes playVLCFile(fileName), so the client and existing implementation have incompatible interfaces.
- A physical travel adapter illustrates the same idea: it can change plug shape and, when needed, voltage.
- Changing a working legacy codebase risks introducing bugs and disrupting other code that already depends on it.
- Changing the client for each legacy API creates hard-coded branches and tighter coupling, such as separate handling for VLC and MP4 players.
- Adapter terminology distinguishes the client, the target interface it expects, the adaptee with the incompatible API, and the adapter between them.
- The adapter implements the target interface so the client can program to MediaPlayer rather than a specific implementation.
- It stores a reference to the legacy VLC player, supplied through its constructor, which the UML diagram represents as aggregation.
- Its play method delegates to playVLCFile on the wrapped object; adapters may also convert arguments when the target and adaptee use different data formats.
- A VLCAdapter and an MP4Adapter each implement MediaPlayer while wrapping their respective legacy player types.
- Each adapter maps play(fileName) to the corresponding legacy method, such as playVLCFile or playMP4File.
- The client can call the same play method for either format, while the adapter routes the call to the correct implementation.
- Adapters apply whenever a client must work with an interface it cannot change, including legacy code and third-party libraries.
- A payment application could normalize different APIs from PayPal, Stripe, Visa, Mastercard, or American Express.
- When a team controls both sides and can design the interface directly, an adapter may be unnecessary; it becomes useful at integration boundaries.
- Dog size and hair length are independent features: small dogs can have long hair, and large dogs can have short hair.
- Modeling every combination with subclasses multiplies the number of classes as options per feature raised to the number of features.
- With two options for each of two dog features, inheritance already requires four subclasses to represent all combinations.
- A single Dog class can store size and hair length as enum fields supplied to its constructor.
- Methods such as getFoodAmount and getGroomingNeeds use those fields to handle different dog configurations at runtime.
- Inheritance remains appropriate for a genuine hierarchy, such as Animal, Mammal, Dog, and Poodle, rather than unrelated feature combinations.
- A graphical window may be plain, bordered, scrollable, or closable, and users may need combinations of those features.
- Java permits implementing multiple interfaces but only extending one class, so a combined bordered and scrollable window cannot simply inherit from both feature classes.
- Three independent yes-or-no features produce 2^3, or eight, possible combinations, encouraging duplicated subclasses and motivating Decorator.
- WindowImpl supplies the base width, while a BorderDecorator implements the Window interface and wraps a Window reference.
- The decorator stores only its additional border thickness rather than duplicating the wrapped window’s width field.
- getWidth adds the two side borders to the base width; setWidth subtracts their thickness before delegating the inner width update.
- A decorator implements the same interface as the component it wraps, allowing clients to use either the base window or a decorated window through the Window type.
- The wrapped reference is typed to the interface, not WindowImpl, so the decorator can accept any Window implementation.
- Because composition is used instead of inheritance, every interface method must be implemented, even when most methods simply delegate.
- PriceTag defines setAmount and getAmount, while PriceTagImpl stores the original amount.
- DiscountedPriceTag implements PriceTag, wraps another price tag, and stores its own discount instead of duplicating the base amount.
- setAmount delegates directly; getAmount retrieves the wrapped price, subtracts the discount, and prevents the result from becoming negative.
- Two decorators applying $20 discounts to a $100 price tag can be chained to produce a $60 result, with each wrapper holding a reference to the previous object.
- The chained wrappers form a linked structure, and getAmount calls travel inward to the base object before each decorator modifies the returned amount.
- An unwrap method can expose the wrapped object, but if unwrap is absent from the PriceTag interface, client code needs a downcast to the concrete decorator type to call it.
- A TextPriceTag interface can extend PriceTag with methods such as getTax, getTaxRate, and getPreTaxPrice.
- The Java I/O library uses decorator-style wrappers around streams and readers, including BufferedInputStream and PushbackInputStream.
- Java input can come from a file or a pipe connected to another program, and decorators add buffering or pushback behavior around that source.
- Decorator order can matter: a closable window may require a border so its close control has an appropriate place.
- A later decorator may be incompatible with the object or feature combination it wraps, so combinations need to be managed carefully.
- Without inheritance, a decorator cannot access a wrapped class’s protected fields; it needs methods such as getters, or broader field visibility, to obtain that data.
Transcript excerpt
0:00 In the last lecture, we started discussing the aspect of object-oriented programming which is referred to as composition over inheritance and that directly relates to the uh the the uh decorator design pattern. Um and before that uh I would like to discuss one other um structural design pattern which is the adapter design pattern which I mentioned in the last lecture and I'd like to squeeze that in first because uh the next assignment which should be coming out before our next lecture and Tuesday is a well-being day. So um that assignment is based on adaptive design pattern. So let's discuss that first and then we'll go ahead and come back to composition or
0:47 inheritance and continue on with the decorator design pattern. So let's discuss uh the adaptive design pattern. Now that is part of the structural design patterns. So, so far we've looked at um we started taking a look at iterator which was part of the behavioral design patterns and that relates to how um classes interrelate and how they communicate and how the responsibilities are divided among themselves. Creational patterns we looked at next and those relate to how you create new classes and objects and structural patterns are a little different and they relate to how you compose different classes and objects together to construct larger
1:35 structures. So now we're heading towards larger structures and we'll take a look at two design patterns today. the adapter design pattern and the decorator. So let's start off with the adapter design pattern. Now the adapter design pattern as is defined by the gang of four uh and I'll read this out to you uh converts the interface of a class into another interface that the client expects. The adapter lets classes work together that couldn't otherwise because
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Muhammad Sayeed Ghani.