Navigation Bar

Wednesday, June 16, 2010

Struts 1.1 - Using Java Design Patterns

 Java design patterns are reusable solutions to commonly occurring software design problems encountered during Java application development. They are not readymade code blocks that can be directly pasted into an application. Instead they serve as structured templates and architectural blueprints for writing clean, flexible, maintainable and loosely coupled object oriented code. You can't find a pattern and copy it into your program, the way you can with off the shelf functions and libraries. The pattern is not a specific piece of code, but a general concept for solving a particular problem. Once you have finalized a pattern, you can follow the pattern details and implement your solution. It makes the flow of code more clear to the programmer, who know which interfaces, classes and methods he needs to create with a proper inter relation between these objects. 

Patterns are often confused with algorithms, because both concepts describe typical solutions to some known problems. While an algorithm always defines a clear set of actions that need to be taken to achieve a goal, a pattern is a higher level description of a solution. The same pattern can be used to solve different problems using different programs and different algorithms.

An analogy to an algorithm can be a cooking recipe: both have clear steps to achieve a goal. On the other hand a pattern is like a blueprint: at a high level you can see what the result and the features of the program are, but the exact implementation of the pattern is upto you, the developer.

These reusable solutions were obtained by trial and error by numerous software developers over quite a substantial period of time. Implementing a good design pattern helps

  • Improve code reusability and maintainability. It thus helps reducing the cost of ownership of the product by reducing time taken to develop enhancements and new features in the product.
  • Provide standard solutions for recurring design problems. It provides an industry-standard approach to solve a recurring problem. Since it is a tried and tested approach there will be lesser points of failure in the project.
  • Enhance communication among developers using common design terminology. It makes the code easy to understand and debug. New members of the team will understand the framework and architecture of the product easily and thus they will be able to become productive team members more quickly.
There are many types of design patterns, each addressing a specific problem or a set of problems.
As shown in the image below, some common types of design patterns include 
  • creational patterns, which deal with object creation; 
  • structural patterns, which focus on object composition and organization.
  • behavioral patterns, which deal with the communication between objects and classes.


The choice of pattern for your product

The choice of pattern to use depends upon many factors primarily the requirement of you project, the scalability, reusability, maintenance. To determine the pattern to use, identify the core content of your requirement or problem and map it to one of the 3 design pattern categories.
Use a creational pattern if your problem is related to complex object instantiation, high resource consumption during creation or constructor overloading.
If your use case involves making incompatible interfaces to work together, managing deep tree like structures, adding responsibility to objects dynamically or making incompatible and unrelated layers to work smoothly together use the Structural pattern.
If your challenge is to use complex if-else algorithms, state dependent behavior, or loose coupling between interacting objects and how they communicate and interact with each other use the Behavioral Pattern.

I will explain in some detail the factory pattern and how I will use it in the StockCode program.

The Factory Design Pattern

It is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.


The Use Case

Imagine a logistics management application that handles transportation by trucks. For this your main class will be a Truck class. This transportation app becomes popular and you are receiving many transportation orders. You now start getting calls to transport goods by freight trains, ships and by flight as well. So now you have to extend this application to incorporate logistics for transport by sea, rail and air. You now need to add ships, trains and planes to your application. Each transport mode has its own features and complexities. Example - Perishable materials like meat and fish over long distances can only be transported by flight. For construction raw materials like cement, sand etc the best mode of transport would be freight trains. You thus need to make lots of changes to your code. You will thus end up writing a code with lots of ifs and elsifs  thus making the code more buggy and bulky to manage and develop.

Solution

The factory pattern suggests that you replace direct object calls (using the new operator) with calls to a special factory method. The objects are still created using the new operator, but are called within the factory method. Based on the mode of transport chosen, automatically the object for that mode will be created having the methods and logic specific to that mode of transport.


You can now change the factory method in a subclass and change the class of products being created by the method. Subclasses for each implementation will now return different types of products only if these products have a common base class or interface.                                                                                          For example - the Truck, Ship, Plane and Train classes should implement the Transport interface, which declares a method called deliver(). Each class implements this method differently.  Truck will deliver a set  cargo by land, Ships will deliver a different set of cargo by sea, planes will deliver a specific niche cargo by air and trains will deliver cargo which is most convenient and economical by train. 

Thus RoadLogistics class returns Truck objects, SeaLogistics class returns ships, AirLogistics class will return cargo plane objects and RailLogistics class will return Train objects. 

The code that uses the factory method (mainly the client code) doesnt see a difference between actual products returned by various subclasses. The client is mainly interested with getting his product withing the time and budget he want. He is oblivious to the mode of transport. For all his products he uses the abstract Transport class. He knows that all transport objects will have the deliver method. But exactly how this delivery happens is not important to the client.

                 



  References 


God's for the day

Those Who Are Worthy of Praise
If you gathered nothing in your youth,
  How can you find anything in your old age?
How attractive is sound judgement in the gray-haired,
  And for the aged to possess good counsel!
How attractive is wisdom in the aged,
  And understanding and counsel in the venerable!
Rich experience is the crown of the aged,
  And their boast is the fear of the Lord.
Sirach 25:3-6

Gospel teachings of Jesus

Jesus again foretells his Death and Resurrection
As they were gathering in Galilee, Jesus said to them, 
 "The Son of Man is going to be betrayed into human hands, and they will kill him, 
and on the third day he will be raised." And they were greatly distressed.
Mathew 17:22-23

No comments:

Post a Comment