Monday, February 1, 2010

The Template Method Pattern

Note: CLICK IMAGE TO ENLARGE.

About
:The Template Pattern uses the inheritance beautifully to take advantage of code reuse. No composition is used because of the strict nature of the circumstances where it should be used. The subclasses are bound to implement the abstract behavior of superclass and give the implementation in their own way and yet the sequence of algorithm is made unchangeable by making the method, of superclass which has the algorithm, final.

Definition : Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

When to use it: When you have a fixed algorithm to execute from a superclass and which must not be changed in sequence but should behave differently in subclass specific way then its good to use this pattern for
1)integrity reason, of the algorithm's sequence
2)code reuse, if there are many subclasses which all depend on superclass implementation of certain functions.

How to use it : In this pattern, a superclass will define a method, which has a fixed sequence in calling some methods, we call it template method or an algorithm. Superclass will have certain methods whose implementation is given by superclass itself and some methods which are defined as abstract, which must be implemented by the subclasses. Define this template method as final in superclass so that, subclasses can not change the sequence of algorithm and still contribute subclass-specific way by giving their own implementation of abstract methods. So the client will call the final method of subclass, inherited from superclass, and get the implementation of the algorithm in the subclass-specific way.

Example : The diagram 1.1 shows the initial design where two different classes has an algorithm which has same sequence of methods but each having its implementation of those methods in their own way. Here, the same code is scattered across the classes.



The diagram 1.2 shows the Template Method Pattern, where we take out the common behavior of subclasses into superclass creating a common point of change which will reflect to all the subclasses. We define the subclass-specific methods in superclass as abstract thus making mandatory for subclass to give implementation. Also, we create a new method, Template Method(on which the name is given to this pattern), by calling the methods in the sequence by which we want our common algorithm to be executed. And , defining it as final so that we are sure that no subclass can change the sequence and just give its own implementation.


Conclusion : To conclude, the sequence,which must be same throughout the subclasses, is defined by the superclass and some part of the algorithm is executed by subclasses such design is a very good example of secure algorithm ensuring fixed sequence but with added touch of subclasses who give implementation differently.

Friday, January 29, 2010

The Adapter Pattern

Note: The word client and caller are used interchangeably in this document which both refer to the class/method which calls the method of another class.

Note: CLICK ON IMAGE TO ENLARGE IT.

About : Being adaptive is at the core of any human activity which requires a person to become conversant to the changing environment. And surprisingly OOP also comes under the same category!!. Many times it happens that the class or interface we are using is not,for any particular reason , compliant with the one which client expects. In such cases the adapter pattern can come to our rescue. It is recommended that you use this pattern wisely in order to avoid unexpected results.

Definition :converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interface.

When to use it: We can use this pattern when, due to compatibility issues the caller does not identify our interface as the one expected by it. Let's say, we have a library provided by our client which expects some interface and your company has ,in past, developed some libraries. Now, in order for our libraries to be used by client-provided libraries they must be compatible. What this pattern does is they MAKE the client SEEM that it is compatible.

How to use it : All we need to do is, create a concrete class which implements the interface which client expects and, delegate the request to the concrete class which implements the interface, which we need to function in response.

Example : The diagram 1.1 illustrates how the request came for a target interface gets delegated to another interface. Here, the client only “looks” at the interface being implemented.



To make the pattern more clear, let's understand it with a real world(confined to Java) example.

We have nice collection interfaces, java.util.Enumeration and java.util.Iterator. Both having methods to iterate through the objects of any of the java.util.Collection subclasses. Now,through the use of Adapter Pattern, we can create an adapter which makes client seem, if not actually make, the objects of java.util.Iterator compatible with objects of java.util.Enumeration. Diagram 1.2 below shows the class diagram for the same.






Conclusion : To summarize, when the “type” expected by the client differs from the one we have, use this pattern. To make components more adaptive,which might not have been otherwise , we can use this pattern to suit to our need.


Any suggestions or queries are welcomed.

Thursday, January 28, 2010

The strategy Pattern

Note: This design pattern and all those which are posted on this blog are written by me after reading the book "Head First Design Patterns" so the definition and understanding of ideas will be from that book. The purpose is to give a concise explanation of the design patterns.For more detailed explanation please refer to the book

Note: CLICK ON THE IMAGE TO ENLARGE IT.

About : A beautiful design pattern which demonstrates how we can ,through the use of composition( HAS-A relation) over inheritance( IS-A relation) , reduce the harmful effects of change in code and make the design more flexible.
We can change behavior at runtime and change the code without affecting the client, which uses them.

Definition : The strategy Pattern defines a family of algorithms, encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

When to use it: when we have common type of behavior in our various subclasses and they may change in future and if the subclasses are too many then we need to change the the behavior by editing each and every class where change is needed. This happens because our implementation is “locked” inside our subclasses and thus whenever change is required we need to change each and every subclass.

How to use it : Identify aspects of our application that vary and separate them from what stays the same. So, by making a loose coupled design through the interface we make the caller unaware of the implementation and thus implementation can change without touching code at the caller side.

Example : Lets say we have a class which has two behaviors one is common to both the subclasses and other is new behavior which is applicable to one subclass which not to the other. So in this case if we depend on inheritance then we have to give empty implementation of the new behavior in the SubClass2. This design is not loosely coupled, implementation is locked inside subclasses. So in case we have to change the new behavior in any subclasses then we need to make changes there. If there were 20 behaviors and 100 subclasses then the changes would be felt worst.



So we'll try to make our design more flexible by introducing interface and removing the things that changes from subclasses and separating that into interface.This change seems convincing as the behavior is made optional through use of interface. The classes which needs this behavior will implement the interface. But still the change in the subclasses will need us to alter the code in the subclasses. Thus ,this design still depends on the implementation given by the subclasses who implement the interface.

Lets improve the design a little bit. This time we'll separate the implementation not through inheritance but through composition.


Now the implementation is separated from the place where it was used. So, any subclass can use any of the XYZBehavior implementation through the reference it holds of XYZable interface. And so the changes made in XYZBehavior implementation does not affect the caller(i.e. Any subclass ).This makes design more flexible.


Conclusion : Separate the functionalities of your application that changes from what stays the same. And prefer to use composition over inheritance when you need a flexible design because interface gives dynamic allocation of objects and loose coupling while inheritance gives implementation which is static inside the class and makes code hard to manage when exposed to changes.

Any suggestions or queries are welcomed.

Sunday, January 11, 2009

New Java ME Confirmation Alert

Hello All,
This Java ME alert I've created which might be helpful while creating project with large amount of Forms.

Description : This example consists of one midlet class , one ConfirmationAlert class and one ConfirmAlertListener interface.

Classes and Interfaces Used:
ConfirmAlertListener : as being interface it has two methods (Contract with implementer class)
1) yesPressed -called on positive command press
2) noPressed -called on negative command press

Note: Here positive and negative word means Positive response(like
"Yes","Ok") and Negative response (like "Cancel","Back")
ConfirmationAlert : this class "Delegates" call and behaves as a bridge between
CommandListener of lcdui(i.e. itself) and
ConfirmAlertListener(i.e. in this case HelloWorld ).

HelloMIDlet : this class uses functionality of ConfirmationAlert class and implements
ConfirmAlertListener interface.

Design Principles Applied:
1) seperation of concern
2) program to interface

Design Pattern Used:
1) Observer Pattern

Benifits:
In a project which has many forms whith which user interacts in that case there are frequent ocassions in which you might feel to ask user for confirmation about some action, in that case this code is very helpful to generate "Quickly" an alert with message and two commands(one for positive and another for negative response).
In addition to quickly creating an custom alert this makes design more simple , just create ConfirmAlert and register your class that's it.

Drawbacks:
Main drawback is as this is for project with more number of forms , it will create two(one class and one interface) components which will take some amount of memory.
So if you are not concerned too much with memory and target devices are having enough memory this will surely help you.
In case where memory is main concern you can surely have "Inner Version" of this class and interface that might help you.

Code:

package hello;
/**
* This listener interface is for alert of type
* confirmations.so the class implementing it is notified when
* specific confirmation response is given by user.
* @author Sandeep Gadhvi
*/
public interface ConfirmAlertListener {
/**
* this method is called when "positive" response is given
* to the alert by user.
*/
public void yesPressed();
/**
* this method is called when "negative" response is given
* to the alert by user.
*/
public void noPressed();
}



package hello;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;

/**
* Confirmation alert to get response from user
* in either positive or negative way.
* @author Sandeep Gadhvi
*/
public class ConfirmationAlert implements CommandListener{

private Alert alert;
private Command positive;
private Command negative;
private ConfirmAlertListener listener;
/**
* constructor for Confirmation alert
* @param msg message to display in alert
* @param positive positive command in confirmation
* @param negative negative command in confirmation
*/
public ConfirmationAlert(String msg,Command positive,Command negative){
this.positive=positive;
this.negative=negative;
alert=new Alert("Confirm Alert",msg,null,AlertType.WARNING);
alert.addCommand(positive);
alert.addCommand(negative);
alert.setTimeout(Alert.FOREVER);
alert.setCommandListener(this);
}
/**
* registers the listener for confirmation alert
* @param listener listener class implementing ComfirmAlertListener
*/
public void setConfirmAlertListener(ConfirmAlertListener listener){
this.listener=listener;
}
/**
* get the alert reference for this ConfirmationAlert
*@return alert for this class
*/
public Alert getAlert(){
return alert;
}
/**
* command action for displayables
* @param command command object reference
* @param display displayable
*/
public void commandAction(Command command, Displayable display) {
if(command==positive){
if(listener!=null){
// call yes pressed method of ConfirmAlertListener implementer class
listener.yesPressed();
}
}
if(command==negative){
if(listener!=null){
// call no pressed method of ConfirmAlertListener implementer class
listener.noPressed();
}
}
}
}



package hello;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
* This is test midlet class which shows how to use "ConfirmationAlert Class"
* and "ConfirmAlertListener Interface", Its a simple "Hello World" program
* but with Logic of Alert and Listener seperated from main code.Thus encapsulating
* the code.
* @author Sandeep Gadhvi.
*/
public class HelloMIDlet extends MIDlet implements CommandListener,ConfirmAlertListener {

private boolean midletPaused = false;

private Command exitCommand;

private Command yesCommand;
private Command noCommand;
private ConfirmationAlert confirmAlert;
private Alert alert;

private Form form;
private StringItem stringItem;

public HelloMIDlet() {
yesCommand=new Command("Yes",Command.OK,1);
noCommand=new Command("No",Command.CANCEL,1);
// create new ConfirmationAlert object with message to show and
// positive command and negative command for corresponding response.
confirmAlert=new ConfirmationAlert("Do You Really Want To Exit?", yesCommand, noCommand);
//don't forget to registern listener as in every event driven architecture.
confirmAlert.setConfirmAlertListener(this);
// get the custom alert
alert=confirmAlert.getAlert();
}

public void startMIDlet() {
switchDisplayable(null, getForm());
}
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {

Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}

}
public void commandAction(Command command, Displayable displayable) {
if(displayable == form){
if (command == exitCommand) {
// on exit command show "Alert" to user
getDisplay().setCurrent(alert);
}
}
}
/**
* This will be called when user presses "Yes" command
*/
public void yesPressed() {
exitMIDlet();
}
/**
* This will be called when user presses "No" command
*/
public void noPressed() {
getDisplay().setCurrent(getForm());
}
public Command getExitCommand() {
if (exitCommand == null) {
exitCommand = new Command("Exit", Command.EXIT, 0);
}
return exitCommand;
}
public Form getForm() {
if (form == null) {
form = new Form("Welcome", new Item[] { getStringItem() });
form.addCommand(getExitCommand());
form.setCommandListener(this);
}
return form;
}
public StringItem getStringItem() {
if (stringItem == null) {
stringItem = new StringItem("Hello", "Hello, World!");
}
return stringItem;
}
public Display getDisplay () {
return Display.getDisplay(this);
}
public void exitMIDlet() {
switchDisplayable (null, null);
destroyApp(true);
notifyDestroyed();
}
public void startApp() {
if (midletPaused) {
} else {
startMIDlet ();
}
midletPaused = false;
}
public void pauseApp() {
midletPaused = true;
}
public void destroyApp(boolean unconditional) {
}
}

Any Suggestions or Comments regarding this article will be appreciated.


Regards,
Sandeep Gadhvi.

Saturday, January 10, 2009

First Blog

Hi All,
Though this is my first blog ,degree of enthusiasm is not so much higher but still I have much much to write in the future.
For those first time visiting my blog I am sandeep gadhvi , from ahmedabad (basically from gandhidham,kutch) doing job at one middle scale IT company at ahmedabad.
For those who are familiar with me you know i don't have anything to write that's why i am filling up this empty space.
So......... Enough is Enough .......This is me you like or not.

We'll meet in future with lots of text pouring out of this blog and your brain pouring out of your head......ha ha ha...

Byee for now "Hasta La Vista".......