Validations through Decorator Pattern

The decorator pattern is a common design pattern often used to add new functionality to an object dynamically. The main benefit of the decorator pattern is that the existing object’s class is not directly modified. This follows the open-closed principle in the Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion design principles, or SOLID for short.

The four participants are:

  1. Component Interface:: Interface for the objects that can have responsibilities added to it dynamically. The component interface defines the operations and properties for the component. In our example ICreditCard
  2. ConcreteComponent: Defines an object implementing Component interface. This is the object that is going to be decorated, but it doesn’t have any knowledge of decoration. The person implementing the decorator may not even have the access to the source code. The concrete component is the primary class you want to extend that implements the component interface. In our example CreditCard.
  3. Decorator: Maintains a reference to the Component object, and defines an interface that conforms to the Component interface. So it contains a reference to the base behavior, and also implements the same interface, hence can be treated as the Component itself. The client code expecting the Component will deal with Decorator without even noticing the difference. In our example CreditCardDecorator.
  4. ConcreteDecorator: This actually adds responsibility to the component. The class that inherits from Decorator and may add some additional specific functionality in the form Validations. In our example CreditCardValidatorBase and CreditCardValidator, CreditCardValidatorBase is just providing Validation functionality and provides validation rules which can be further extended by sub classes if required.

Decorator

Attached is the Source Code Sample

Validation Through Decorator Pattern

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s