SECTION 04 / 6

Structural design patterns

2 min read
On this page 3 headings

Structural patterns help assemble objects and classes into larger structures while keeping them flexible and efficient.

4.1 Facade: one simple entry point to a complex workflow

Facade Pattern
Facade Pattern
Open image ↗
Facade Pattern

Problem: you must create several objects and perform several steps in the right order with the right parameters, using existing complicated library functions. Anyone reusing your code must know all of this. After a buyer places an order: create order, notify seller, prepare packaging, send for delivery — classes Order, Seller, Package, Delivery.

Facade provides a simple interface to a library or complex set of classes: DeliveryFacade.deliver(...) creates the objects and calls them in order; the client calls only deliver.

Pro: isolates code from other libraries’ and classes’ complexity. Con: the facade is tightly coupled to other objects, so maintenance is harder; any change in Order/Seller/Package/Delivery needs a change in DeliveryFacade.

4.2 Adapter: connect incompatible interfaces

Adapter Pattern
Adapter Pattern
Open image ↗
Adapter Pattern

Problem: some products cost dollars/euros and must be converted to rupees, but Product cannot directly use the existing ConversionCalculator library because its interface is incompatible and not under our control. The client calls the adapter’s method; the adapter calls the adaptee’s method, wrapping the object and hiding the incompatibility.

CostCalculatorAdapter takes a product, creates a ConversionCalculator and passes the cost. Product creates the adapter and gets the cost in rupees (example: $300).

Pros: SRP — conversion code is separated from Product’s business logic; OCP — new adapters for other currencies. Con: overall code complexity increases, and it is unnecessary if you could change Product or access ConversionCalculator directly.

4.3 Facade versus Adapter

Facade vs Adapter
Facade vs Adapter
Open image ↗
Facade vs Adapter

Facade gives a simple interface to many classes; Adapter makes incompatible interfaces work together.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑