Wednesday, September 18, 2013

Decorator Design Pattern Example

Decorator Design Pattern: The Decorator design pattern adds additional responsibilities to an object dynamically without affecting other objects or existing objects. It is like a wrapper on another object.

In other words, The decorator pattern is used to extend (decorate) the functionality of a certain object statically, or dynamically.

The decorator pattern is an alternative to subclassing. We can write a subclass by extending a class and add behavior at compile time, and the change affects all object instances of the original class. 
But we can achieve this same behavior without extending a class and using a decorator class, since decorating can provide new behavior at run-time for individual objects.

Lets take an example to understand it.
Problem: We need to read a text file and display its content on screen. So we can write a InputReader class which will take a file as input and read the text file and display the content.

Now suppose:
  1. The given file has text with lots of extra white spaces, So using this InputReader how we can read the file and display the text by removing extra white spaces.  i.e "abc       xyz" shoud be displayed as "abc xyz".
  2. The given text file is an encrypted file and before displaying the text on screen it has to be decrypt. So using the InputReader class how we can achieve this?....


Sunday, September 15, 2013

Command Design Pattern Example

Command Design Pattern:  The Command pattern is known as a behavioral pattern and is used to represent and encapsulate all the information required to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters. Command pattern allows the requester of a particular action to be decoupled from the object that performs the action.


The Command Pattern is useful when we need to do the following task:
  • A history of actions is needed
  • You need callback functionality, like listeners in java
  • Calls or Requests need to be handled at different times or in different orders
  • The invoker should be decoupled from the object handling the invocation.

Lets take an example, Suppose we have an electric engine and we want to start and stop this engine on press or click of a button. We will use command patter to do this...