Tuesday 16 October 2007

Design Patterns (Strategy Pattern)


By : Saif Ikram

Published on : 16-October-2007



Introduction


As we all have a brief idea of what design patterns and what role it plays in the Software Development Life Cycle. Now we will look into one of the most important pattern known as "Strategy Pattern". Lets start up with an example.

In this Article we will also use the following design principles:


  • Identify the aspects of your application that vary and separate them from what stays the same.
  • Program to an interface, not an implementation
  • Favor Composition over inheritance

Problem (WorldCarSimulator)

A simulator which demonstrates the types of worldwide cars and their features. Users can choose any type of cars, then the simulator should give a demonstration of the type of car selected with the features available for that car.

Start with the basic design

Consider the following basic design:

Here Car is the base class. Taxi and RentedCar’s are the derived classes. Carry() is defined in base class and run() is overridden in the derived classes as required. Suddenly you recognise that, as this is for worldwide cars, there are some cars, which go for race.

Only change required is to add a race() method in the base class so some cars can go for the race.

Update the code with race() method and now the code is ready for demo.

User starts the Demo, Some thing went horribly wrong.

"Taxi’s started racing"

"RaceCar’s started carrying passengers"


Now code needs to be modified. I.e.

Modify Taxi Class

  • Race() to do nothing

Modify RaceCar Class
  • Carry() to do nothing



Consider about ToyCar they do not race Nor they do not Carry


I.e.

  • Create the ToyCar Class
  • Race() to do nothing
  • Carry() to do nothing

As long as new type of car’s come, the more modification is required. Let us think about some alternative solution like the following below.







In the above design, there is no reusability. As long as you add classes you need to override the methods carry() or race() etc. so this is not a good design.

Let us use Design Principle one:

"Identify the aspects of your application that vary and separate them from what stays the same"



Like this :

And one more thing we are using classes where in we do not have a chance for dynamic behaviour. Ie. for example Taxi started taking passengers and after some time it want to go for a race, which is not possible as per the last design.Ok. Lets implement the second design principle

"Program to an interface, not an implementation"

Let see the design now using the two principles:



We just had designed for the behaviour of Car’s like Carry, Race etc.. Now we need to design the Types of Cars. It’s now time to use the third principle.

"Favor Composition over inheritance"

Here is the final design:


At last we had implemented the first design pattern

"Strategy Pattern"

"Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."


Now the code walk through:

Car Class



Public abstract class Car {

CarryBehaviour carryBehaviour;
RaceBehaviour raceBehaviour;

public Car(){
}

public abstract void run();

public void race(){
raceBehaviour.race();
}

public void carry(){
carryBehaviour.carry();
}

public void setraceBehaviour(RaceBehaviour rb){
raceBehaviour = rb;
}

public void setcarryBehaviour(CarryBehaviour cb){
carryBehaviour = cb;
}
}


RaceBehaviour (Interface), RaceCar (Class) & RaceNoWay (Class):



public interface RaceBehaviour{
public void race();
}

public class RaceCar implements RaceBehaviour{

public void race(){
system.out.println(“I am racing”);
}
}

public class RaceNoWay implements RaceBehaviour{

public void race(){
system.out.println(“I can’t race”);
}
}

CarBehaviour (Interface), CarryPeople (Class) , NonCarrier (Class) & CarryLoad (Class):



public interface CarryBehaviour{
public void carry();
}

public class CarryPeople implements CarryBehaviour{

public void carry(){
system.out.println(“I can carry only people”);
}
}

public class NonCarrier implements CarryBehaviour{

public void carry(){
system.out.println(“I can’t carry”);
}
}

public class CarryLoad implements CarryBehaviour{

public void carry(){
system.out.println(“I can carry only Load”);
}
}

Car Class


Public class Taxi extends Car {

public Taxi(){
carryBehaviour = new CarryPeople();
raceBehaviour = new RaceNoWay();
}

public void run(){
System.out.println(“Running a Taxi”);
}
}

Jeep Class



Public class Jeep extends Car {

public Taxi(){
carryBehaviour = new CarryLoad();
raceBehaviour = new RaceNoWay();
}

public void run(){
System.out.println(“Running a Jeep”);
}
}

RaceCar Class



Public class RaceCar extends Car {

public Taxi(){
carryBehaviour = new NonCarrier();
raceBehaviour = new RaceCar();
}

public void run(){
System.out.println(“Going for Race”);
}
}

ToyCar Class



Public class ToyCar extends Car {

public Taxi(){
carryBehaviour = new NonCarrier();
raceBehaviour = new RaceNoWay();
}

public void run(){
System.out.println(“Play with ToyCar ”);
}
}

RentalCar Class


 
Public class RentalCar extends Car {

public Taxi(){
carryBehaviour = new CarryPeople();
raceBehaviour = new RaceNoWay();
}

public void run(){
System.out.println(“I am Rented Car”);
}
}


Small Demo



 
Public class WorldCarSimulator {

public static void main(string[] args){

Car Ferrari = new RaceCar();
Ferrari.carry();
Ferrari.race();
Ferrari.run();

Car RoadRunnerTaxi = new Taxi();
RoadRunnerTaxi.carry();
RoadRunnerTaxi.race();
//Changing the behaviour dynamically
RoadRunnerTaxi.setraceBehaviour(new RaceBehaviour());
RoadRunnerTaxi.race();

}

}

Strategy Pattern Explained



Participants

The classes and/or objects participating in this pattern are:


  • Strategy (SortStrategy) : declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy
  • ConcreteStrategy (QuickSort, ShellSort, MergeSort) : implements the algorithm using the Strategy interface
  • Context (SortedList) : is configured with a ConcreteStrategy object
  • maintains a reference to a Strategy object : may define an interface that lets Strategy access its data.
  • Observer (IInvestor) :defines an updating interface for objects that should be notified of changes in a subject.
  • ConcreteObserver (Investor) :maintains a reference to a ConcreteSubject object stores state that should stay consistent with the subject's implements the Observer updating interface to keep its state consistent with the subject's

Wednesday 10 October 2007

Wap Introduction

Brief Introduction to WAP

By : Satish Doranahalli
Published on : 09-October-2007

Coding and viewing the pages on mobile device always interests to me, thought to share something about WAP


The Wireless Application Protocol

The WAP protocol is the leading standard for information services on wireless terminals like digital mobile phones.The WAP standard is based on Internet standards (HTML, XML and TCP/IP). It consists of a WML language specification, a WMLScript specification, and a Wireless Telephony Application Interface (WTAI) specification.The WAP Forum founded in 1997 by Ericsson, Motorola, Nokia, and Unwired Planet publishes WAP. Forum members now represent over 90% of the global handset market, as well as leading infrastructure providers, software developers and other organizations.

Protocol Structure

The WAP protocol family mirrors the layered OSI stack, and like the OSI stack some layers are not mandatory. At the lowest level, the WAP Datagram Protocol (WDP) moves information from receiver to sender and is modeled after UDP as a least effort method of delivery. On top of WDP sits the WAP Transaction Protocol (WTP) which ensures that the data fragments sent over the line are actually received, through typical ACK/NACK communication. Higher up, the WAP Session Protocol (WSP) handles the session between communicating systems. All sessions are granted unique IDs and are started/stopped/terminated accordingly.

WAP Micro Browsers

To fit into a small wireless terminal, WAP uses a Micro Browser.A Micro Browser is a small piece of software that makes minimal demands on hardware, memory and CPU. It can display information written in a restricted mark-up language called WML. The Micro Browser can also interpret a reduced version of JavaScript called WMLScript.


What is WML?

WML stands for Wireless Markup Language. It is a mark-up language inherited from HTML, but WML is based
on XML, so it is much stricter than HTML.WML is used to create pages that can be displayed in a WAP browser. Pages in WML are called DECKS. Decks are constructed as a set of CARDS.

What is WMLScript?

WML uses WMLScript to run simple code on the client. WMLScript is a light JavaScript language. However, WML scripts are not embedded in the WML pages. WML pages only contain references to script URLs. WML scripts need to be compiled into byte code on a server before they can run in a WAP browser.

In General uses of WAP

- Checking train table information
- Ticket purchase
- Flight check in
- Viewing traffic information
- Checking weather conditions
- Looking up stock values
- Looking up phone numbers
- Looking up addresses
- Looking up sport results

In my next article I will write about how the simple, tiny, light weight pages are created and how the navigation between the pages are done.

Tuesday 9 October 2007

More Design Patterns


More on design patterns


By : Saif Ikram

Published on : 09-October-2007



Introduction


"Pattern is a recurring solution to a standard problem" as per "Christopher Alexander"


"Each Pattern describes a problem which occurs over and over again in our environment and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice".


What is Design Patterns?


Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Design patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.


Design patterns make it easier to reuse successful designs and architectures.


In General pattern has four essential elements:



  • Pattern Name :Naming a pattern immediately increases our design vocabulary. It let's design at a higher level of abstraction.
  • Problem :It explains the problem and its context. It might describe specific design problems such as how to represent algorithms as objects.
  • Solution : The solution describes the elements that make up the design, their relationships, responsibilities, and collaborations.
  • Consequences : The consequences are the results and trade-offs of applying the pattern

Why Design Patterns?

Design Pattern systematically names, explains, and evaluates an important and recurring design in object-oriented systems. Design patterns capture design experience in a form that people can use effectively. Design patterns make it easier to reuse successful designs and architectures. Expressing proven techniques as design patterns makes them more accessible to developers of new systems

Design patterns help you choose design alternatives that make a system reusable and avoid alternatives that compromise reusability. Design patterns can even improve the documentation and maintenance of existing systems by furnishing an explicit specification of class and object interactions and their underlying intent.


What Experienced Programmers do?


Experienced programmers not to solve every problem from first principles. Reuse solutions that have worked for them in past, when they find a good solution, they use it again and again. Consequently, well find recurring patterns of classes and communicating objects in many object-oriented systems


Benefits


Design patterns have two major benefits.


  • First, they provide you with a way to solve issues related to software development using a proven solution. The solution facilitates the development of highly cohesive modules with minimal coupling. They isolate the variability that may exist in the system requirements, making the overall system easier to understand and maintain.
  • Second, design patterns make communication between designers more efficient. Software professionals can immediately picture the high-level design in their heads when they refer the name of the pattern used to solve a particular issue when discussing system design.

Using Design Patterns in UML


Ok so you might ask how does a pattern relate to the UML?


The patterns that we encounter need to be captured and documented in a sufficiently descriptive manner so that they can be referred for future use. UML provides the perfect tools to do just this.


The class diagram in UML can be used to capture the patterns identified in a system. In addition, UML has a sufficiently extensive and expressive vocabulary to capture the details of patterns. Building on this background we will see how to leverage the usefulness of well-known patterns to make application designing a lot easier.


To sum up, a pattern should have the following characteristics


  • Useful Solution
  • Reusable
  • Contextual
  • Pattern Forms


To give you a head start, the design patterns can provided in two forms:



  • Structural : Structural code uses type names as defined in the pattern definition and UML diagrams.
  • Real-world : Real-world code provides real-world programming situations where you may use the patterns

Types of Patterns


The Gang of Four (GOF) patterns is generally considered the foundation for all other patterns.


They are categorised in three groups:



  • Creational
  • Structural
  • Behavioural

Catalogue of Design Patterns





Creational Patterns


Creational class patterns defer some part of object creation to subclasses, while Creational object patterns defer it to another object.



  • Abstract Factory : Creates an instance of several families of classes
  • Builder : Separates object construction from its representation
  • Factory Method : Creates an instance of several derived classes
  • Prototype : A fully initialised instance to be copied or cloned
  • Singleton : A class of which only a single instance can exist


Structural Patterns


The Structural class patterns use inheritance to compose classes, while the Structural object patterns describe ways to assemble objects.



  • Adapter : Match interfaces of different classes
  • Bridge : Separates an object's interface from its implementation
  • Composite : A tree structure of simple and composite objects
  • Decorator : Add responsibilities to objects dynamically
  • Facade : A single class that represents an entire subsystem
  • Flyweight : A fine-grained instance used for efficient sharing
  • Proxy : An object representing another object


Behavioural Patterns


The Behavioural class patterns use inheritance to describe algorithms and flow of control, whereas the Behavioural object patterns describe how a group of objects co-operate to perform a task that no single object can carry out alone.



  • Chain of Responsibility. : A way of passing a request between a chain of objects
  • Command : Encapsulate a command request as an object
  • Interpreter : A way to include language elements in a program
  • Iterator : Sequentially access the elements of a collection
  • Mediator : Defines simplified communication between classes
  • Memento : Capture and restore an object's internal state
  • Observer : A way of notifying change to a number of classes
  • State : Alter an object's behaviour when its state changes

Monday 8 October 2007

What are design patterns?


By : Saif Ikram

Published on : 08-October-2007



Design patterns are recurring solutions to software design problems that you find again and again in real-world application development. Design patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.

Design patterns make it easier to reuse successful designs and architectures.

In general, a pattern has four essential elements:


  • Name – Naming a pattern immediately increases our design vocabulary. It allows design at a higher level of abstraction.

  • Problem – This element explains the problem and its context. It might describe specific design problems such as how to represent algorithms as objects.

  • Solution – The solution describes the elements that make up the design, their relationships, responsibilities, and collaborations.

  • Consequences – The consequences are the results and trade-offs of applying the pattern.


Why design patterns?


A design pattern systematically names, explains, and evaluates an important and recurring design in object-oriented systems. Design patterns capture design experience in a form that people can use effectively and make it easier to reuse successful designs and architectures. Expressing proven techniques as design patterns makes them more accessible to developers of new systems.

Design patterns help you choose design alternatives that make a system reusable and avoid alternatives that compromise reusability. They can even improve the documentation and maintenance of existing systems by furnishing an explicit specification of class and object interactions and their underlying intent.

Benefits


Experienced programmers do not to solve every problem from first principles. Instead they reuse solutions that have worked for them in past and when they find a good solution, they use it again and again. Consequently, we find recurring patterns of classes and communicating objects in many object-oriented systems

Design patterns have two major benefits. First, they provide a way to solve issues related to software development using a proven solution which facilitates the development of highly cohesive modules with minimal coupling. They isolate the variability that may exist in the system requirements, making the overall system easier to understand and maintain.

Second, they make communication between designers more efficient. Software professionals can immediately picture the high-level design in their heads when they refer the name of the pattern used to solve a particular issue when discussing system design.

Using design patterns in UML


How does a pattern relate to the UML?

The patterns that we encounter need to be captured and documented in a sufficiently descriptive manner so that they can be referred to for future use. UML provides the perfect tools to do just this.

The class diagram in UML can be used to capture the patterns identified in a system. In addition, UML has a sufficiently extensive and expressive vocabulary to capture the details of patterns. Building on this background we will see how to use well-known patterns to make application design a lot easier.

To sum up, a pattern should have the following characteristics:


  • Useful Solution

  • Reusable

  • Contextual


Pattern forms


To give you a head start, design patterns can be provided in two forms:

  • Structural – Structural code uses type names as defined in the pattern definition and UML diagrams.

  • Real-world – Real-world code provides real-world programming situations where you may use the patterns.


The Gang of Four (GOF) patterns are generally considered the foundation for all other patterns. They are categorised into three groups:

Creational Patterns

Creational class patterns defer some part of object creation to subclasses, while Creational object patterns defer to another object.


  • Abstract Factory – Creates an instance of several families of classes

  • Builder – Separates object construction from its representation

  • Factory Method – Creates an instance of several derived classes

  • Prototype – A fully initialised instance to be copied or cloned

  • Singleton – A class of which only a single instance can exist


Structural Patterns

The Structural class patterns use inheritance to compose classes, while the Structural object patterns describe ways to assemble objects.


  • Adapter – Match interfaces of different classes

  • Bridge – Separates an object’s interface from its implementation

  • Composite – A tree structure of simple and composite objects

  • Decorator – Add responsibilities to objects dynamically

  • Façade – A single class that represents an entire subsystem

  • Flyweight – A fine-grained instance used for efficient sharing

  • Proxy – An object representing another object


Behavioural Patterns

The Behavioural class patterns use inheritance to describe algorithms and flow of control, whereas the Behavioural object patterns describe how a group of objects co-operate to perform a task that no single object can carry out alone.


  • Chain of Responsibility – A way of passing a request between a chain of objects

  • Command – Encapsulate a command request as an object

  • Interpreter – A way to include language elements in a program

  • Iterator – Sequentially access the elements of a collection

  • Mediator – Defines simplified communication between classes

  • Memento – Capture and restore an object’s internal state

  • Observer – A way of notifying change to a number of classes

  • State – Alter an object’s behaviour when its state changes