Decorator design pattern [Structural]

The Decorator Design Pattern allows adding new behavior to existing types. We can extend the functionality of the type without modifying its implementation which is a flexible alternative to subclassing.

The Decorator can be implement via wrapping the object to be enhanced. Extensions provide the ability to add additional methods to types without having to suppress or change their source code.

The Decorator Design Pattern adds new responsibilities to objects without modifying the code of the type used to create them

Example:

A Basic Color class lets you create color with RGB and HSB. What if I have to create color using hex values? Typically we subclass. Instead of subclassing we need to extend the same color class and add a function to create color with hex values.

Another example would be when ordering food online a typical burger or subway sandwich would cost x then user also has options to add extra cheese or steak. Sometimes the vendor provides option to add a drink to the cart. All this adding extras would cost additional charges. The final cost is caluclated with calling the decorators to add their cost to the cart over the base item.

Common misuses: Accidentally replacing the existing functionality of a type. Another misuse is that we may change the original purpose of a type by decorating it with unrelated behavior.

 

 

Bridge Design Pattern [Structural]

Why? Increasing feature set explode class hierarchies. The Bridge pattern dissolves complex class hierarchies by separating common and specific functionality into different hierarchies.

In a typical software development as we add new features, the number of subclasses increases at an alarming rate. By decoupling an implementation from an interface, both can vary independently.

Goal is to separate out common functionality and specific ones.

The bridge pattern separates the abstraction from its implementation and reduces the impact of the changes.

Example:

Consider 2 classes – GroupChat & DirectChat. Now if these were in plain chat format. Then you get a requirement to add support for Secure Chat and Self-destructing chat, now general tendency is to extend the each chat into 2 others SecureGroupChat and SelfDestructGroupChat also SecureDirectChat and SelfDestructDirectChat. Now consider if there is another type of chat – BroadcastChat and we need to extend this to SecureBroadcastChat and SelfDestructBroadcastChat. Now we have a total of 9 classes.

Brdge pattern – solves this with interfaces and a bridge between the interface.

Bridge.jpg

Using bridge pattern all Chat classes implement ChatInterface which will include a MessageInterface. On the other side all 3 Secure, SelfDestruct and Plain Message types will conform to MessageInterface.

Advantages:

  1. Separates Common and specific functionality
  2. Increases Cohesiveness
  3. Removes inheritence (hierarchies)
  4. Removes tight coupling
  5. Reduces number of classes