Decorator and Strategy

Both patterns involve passing one object into another object’s constructor. But their intent is completely different.

  • In the Decorator (Structural), the objects are the same type (Coffee). You inject a Coffee into a Coffee to make a bigger Coffee.

  • In the Strategy (Behavioral), the objects are different types. The CheckoutCart takes a PaymentStrategy so it can hand off the work.

Factory vs. Builder

Both of these patterns exist to solve the same problem: creating objects using the new keyword has gotten too messy. But their intent is completely different.

  • Factory (Creational) is about deciding which object to create. You give it a simple instruction, and it hands you a finished product.

  • Builder (Creational) is about configuring an object. The object is too complex to build in one step, so you assemble it piece by piece.

Factory is a vending machine (press a button, get a standard item). Builder is a subway sandwich shop (walk down the line and customize every ingredient).

Proxy (Structural) vs. State (Behavioral)

Structurally, these two look identical. In both patterns, Object A holds a reference to Object B, and when you call a method on Object A, it delegates the work to Object B.

  • Proxy (Structural) intercepts a call to control access to the real object (e.g., lazy loading, caching, security).

  • State (Behavioral) changes the internal object to change the rules based on the object’s current lifecycle phase.

Notice: The Proxy represents one unchanging thing (the database). It just sits in front as a bouncer. Notice: The Order object is constantly swapping out its internal state OrderState as it moves through its lifecycle. It isn’t acting as a bouncer; it’s undergoing a metamorphosis.

Facade vs. Mediator

This is another classic pairing that causes a lot of confusion because, at a glance, both patterns involve a central class that talks to a bunch of other classes.

  • The difference comes down to the direction of communication and who knows about whom.

Here is the quickest way to separate them:

  • Facade (Structural) is a one-way street. It acts as a simplified front door to a complex subsystem. The subsystem has no idea the Facade exists.

  • Mediator (Behavioral) is a traffic cop in the middle of an intersection. It sits between multiple peer objects (colleagues) to stop them from talking directly to each other. The objects must know about the Mediator to function.

If you are ever looking at a piece of code and trying to figure out if it is a Facade or a Mediator, look at the dependency injection:

  • Facade: The central class knows about the workers, but the workers do not know about the central class. (One-way communication).

  • Mediator: The central class knows about the workers, AND the workers do know about the central class. (Multi-directional communication).