Java Vibes..

June 24, 2009

Structural Patterns

  • Proxy could be used when you want to lazy-instantiate an object, or hide the fact that you’re calling a remote service, or control access to the object.

  • Decorator is also called “Smart Proxy.” This is used when you want to add functionality to an object, but not by extending that object’s type. This allows you to do so at runtime. Java I/O reader, writers are a fine example of this.


  • Adapter the adapter design pattern (often referred to as the wrapper pattern or simply a wrapper) translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces. Adapter is used when you’re trying to unify the interfaces of some incompatible classes that already exist. The Adapter functions as a kind of translator to implementations that could be considered legacy.


  • Facade is a higher-level (read: simpler) interface to a subsystem of one or more classes. Think of Facade as a sort of container for other objects, as opposed to simply a wrapper.
  • Bridge is very similar to Adapter, but it is used for code that is more likely to be greenfield. We call it Bridge when you define both the abstract interface and the underlying implementation i.e. you’re not adapting to some legacy or third-party code, you’re the designer of all the code but you need to be able to swap out different implementations.

Perhaps the most confusing of these is Bridge, here is how a wise guy has tried to define it:

The Bridge pattern is an application of the old advice, “prefer composition over inheritance”. It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn’t subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? You would prefer to say that each Shape has a Color and to implement a hierarchy of colors, and that is the Bridge Pattern.

Here is an example of a Bridge:



PersistenceImplementor implementor = null;
if (true){
	implementor = new DabatasePersistenceImplementor();
	implementor = new FileSystemPersistenceImplementor();
Persistence persistenceAPI = new PersistenceImp(implementor);
Object o = persistenceAPI.findById("12343755");
// do changes to the object then persist

    Blog at