Wednesday 16 June 2010

view Helper Design pattern

Problem:
Presentation tier changes occur often and are difficult to develop and maintain when business data access logic and presentation formatting logic are interwoven. This makes the system less flexible, less reusable, and generally less resilient to change. Inter mingling the business and systems logic with the view processing reduces modularity and also provides a poor separation of roles among web production and software development teams.

 JSP pages consist of HTML and images used to present content to the user. If these pages need to display dynamic content stored in the model then you'd probably embedded some java code(using scripting elements) within these pages to display model data. Adding java code inside JSP pages kills the readability of the JSP program or pages and also gives complexity to programmers towards adding java code.

Solutions:

Implement View Helper design pattern, which says develop JSP programs of web application as java codeless JSP programs. For this we have to use only tags in JSP programs.

Example program for MVC2 Architecture or MVC2 design pattern

Example program for MVC1 Architecture or MVC1 design pattern


mvc design pattern

MVC1 & MVC2 Design Patterns:

In order to develop web applications in easily manner & to reduce the complexity in architectural design and to increase flexibility and maintainablility of code we require some standard appraoach.
That’s why we use MVC design pattern in our applications. They are 2 types of MVC design patterns. They are: MVC1 AND MVC2.

In MVC1, M Stands for Model, V stands for view and c stands for Controller.
In general we use AWT, SWINGS, HTML, JSP, Velocity, Free Marker technologies to develop View part. To prepare Model part we use technologies like JDBC, Hibernate and EJB ETC., and to prepare Controller part we use technologies like Servlets, JSP, EJB etc.

MVC1 Model:
In MVC1  model, we will use a JSP component as controller and as view part.
In MVC1 , WE will use a JSP component to pick up all the requests came from clients, So that it called as JSP front.
In MVC1, we will use a JSP component to control the entire web application, So that it is called as Page-Centric Architecture.
DrawBacks:
1.       In MVC1 , we will use JSP COMPONENT to control the web application and to generate response. So that there is no clear cut separation between the components which are used for controlling and which are used for presentation.
2.       MVC1 model, we will use a JSP COMPONENT to control the entire web application but the existed JSP components may not be sufficient, still there may be a requirement to provide java code inside the JSP pages, which is against to JSP principles.
Due to these reasons we should go for an alternative for designing web applications i.e: MVC2 Model.  






MVC 2 MODEL:




  • In MVC2, we should use a Servlets as controller, set of  JSP PAGES as View part and JDBC Hibernate and EJB ETC OR Java Beans for Model part.
  • In MVC2, we will use a Servlets to trap all the requests came from clients, So that it called as Servlets Front.
  • In MVC2, we will use a Servlets to control the entire web application, So that it is called as Servlet-Centric Architecture.
Advantages:

  • In MVC2 , there is a clear cut separation between the components which we are used for controlling and which we are used for presentation.
  • MVC2 model will provide loosely coupled design in 2 -Tier architecture for web applications.

Example program for MVC2 Architecture or MVC2 design pattern

Note: Struts is framework, which was designed on the basis of MVC2 or simply MVC architecture only
MVC Rules and Regulations:

 to design any web applications on the basis of MVC Architecture or model we should follow the following rules and regulations.


  • In MVC based web applications we should not misuse the components i.e we should not use servlets to prepare view part and we should not use JSP components for controller part.
  • In MVC based we applications web applications, we should not access view part and model part directly.
  • In MVC based web applications controller and view should not interact with the database directly, they should interact with the data base through model part only.
  • In MVC architecture, controller may interact with model part for the sake of setting the data only not for the sake of the getting the data and view part will interact with model part for the sake of getting the data only not for the sake of the setting the data.
  • There is no limitation on the number of JSP pages utilization in view part but all the JSP pages should be java codeless
  • In MVC based web applications, we should not provide page-to-page navigation, we should provide page-controller-page navigation
  • we should use only one servlets as controller but we may use many more number of JSP pages as view part.

Sunday 13 June 2010

Design Pattern Programs

Example program on Java Abstract Factory Pattern

Java Abstract Factory Pattern is the collection of factories. We will understand this factory pattern by a simple use case. Look at the below use case diagram for Java Abstract Factory Pattern.

we have created two factories, Subject and Game factory. The Abstract Factory will contain these two factories. Lets have a look at the codes of implementation of this Abstract Factory Pattern.

First we will create Subject Factory
Subject.java
public interface Subject {
 int getMarks();
}


Arts.java
public class Arts implements Subject {

 @Override
 public int getMarks() {
  return 70;
 }
}



Maths.java
public class Maths implements Subject {

 @Override
 public int getMarks() {
  return 80;
 }
}


Science.java
public class Science implements Subject {

 @Override
 public int getMarks() {
  return 90;
 }
}

Next step is to create Game factory:


Game.java
public interface Game {
 void getGameName();
}

Football.java

public class Football implements Game {

 @Override
 public void getGameName() {
  System.out.println("I play Football !!!");
 }
}

Cricket.java

public class Cricket implements Game {

 @Override
 public void getGameName() {
  System.out.println("I play Cricket !!!");
 }
}

Rugby.java

public class Rugby implements Game {

 @Override
 public void getGameName() {
  System.out.println("I play Rugby !!!");
 }
}

Now we will create Abstract class – AbstractStudentFactory.java

AbstractStudentFactory.java

public abstract class AbstractStudentFactory {
 abstract Subject getMarks(String subjectName);
 abstract Game getGameName(String gameName);
}

Two other Factory Classes
SubjectFactory.java



public class SubjectFactory extends AbstractStudentFactory {

   @Override
   public Subject getMarks(String subjectName){
  
      if(subjectName == null){
         return null;
      } 
     
      if(subjectName.equalsIgnoreCase("Maths")){
         return new Maths();
        
      }else if(subjectName.equalsIgnoreCase("Science")){
         return new Science();
        
      }else if(subjectName.equalsIgnoreCase("Arts")){
         return new Arts();
      }
     
      return null;
   }
  
   @Override
   Game getGameName(String gameName) {
      return null;
   }
}

GameFactory.java

package com.tech2money.abstractfactory;

public class GameFactory extends AbstractStudentFactory {

   @Override
   public Game getGameName(String gameName){
  
      if(gameName == null){
         return null;
      } 
     
      if(gameName.equalsIgnoreCase("Football")){
         return new Football();
        
      }else if(gameName.equalsIgnoreCase("Cricket")){
         return new Cricket();
        
      }else if(gameName.equalsIgnoreCase("Rugby")){
         return new Rugby();
      }
     
      return null;
   }
  
   @Override
   Subject getMarks(String subjectName) {
      return null;
   }
}

Now we will create Factory creator class – Factory.java

package com.tech2money.abstractfactory;

public class Factory {
   public static AbstractStudentFactory getFactory(String type){
  
      if(type.equalsIgnoreCase("Subject")){
         return new SubjectFactory();
        
      }else if(type.equalsIgnoreCase("Game")){
         return new GameFactory();
      }
      return null;
   }
}

AbstractFactoryImpl.java

public class AbstractFactoryImpl {
 public static void main(String[] args) {

  AbstractStudentFactory subjectFactory = Factory.getFactory("Subject");

  Subject sub1 = subjectFactory.getMarks("Maths");
  System.out.println(sub1.getMarks());
 
  Subject sub2 = subjectFactory.getMarks("Science");
  System.out.println(sub2.getMarks());

  Subject sub3 = subjectFactory.getMarks("Arts");
  System.out.println(sub3.getMarks());

  AbstractStudentFactory gameFactory = Factory.getFactory("Game");

  Game game1 = gameFactory.getGameName("Football");
  game1.getGameName();
 
  Game game2 = gameFactory.getGameName("Cricket");
  game2.getGameName();
 
  Game game3 = gameFactory.getGameName("Rugby");
  game3.getGameName();
 }
}


Tuesday 8 June 2010

Example program for Factory Pattern

Factory Pattern

Factory Pattern:
sometimes, an Application (or framework) at runtime, can not anticipate (getting) the class of object that it must create
The application (or. framework) may know that it has to instantiate classes, but it may only know about abstract classes (or interfaces), which it can not instantiate. Thus the application class may only know when it has to instantiate a new object of a class, not what kind of subclass to create.

Hence a class may want it's subclasses to specify the objects to be created.

The factory pattern design pattern handles these problems by defining a separate method for creating the objects, these methods optionally accept parameters defining how the object is created, and then return the created object.

Problem:

Creating multiple objects for multiple subclasses and utilizing one of them based on the supplied data is wrong methodology because the remaining objects became unnecessarily created objects.

Solutions:
use Factory Pattern, here the method of super class or some other class instantiates/creates one of the several sub classes objects based on the supplied data provided by user (at compile time/ at run time) that means objects for remaining sub classes will not be created.

Def:
  Define an interface for creating an object, but let the sub classes decide which class to instantiate. The Factory Method lets a class defer instantiation to sub classes.
 A Simple Factory pattern return an instance of one of several possible (sub) classes depending on the data provided to it. Usually all classes that it returns have a common parent class and common methods, but each performs a task differently and is optimized for different kinds of data.

Intent:

  •  creates objects without exposing the instantiation logic to the client.
  • Refers to the newly created object through a common interface
Application Areas:


  • A class can not anticipate the class of objects it must create.
  • A class specifies its sub-classes to specify which objects to create.
  • In programmer's language, you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.
Ex:

In JDBC APPLICATIONS , DriverManager.getConnection(-,-,-) method logic is nothing but factory pattern logic because based on the argument values that are supplied, it creates and returns one of the JDBC driver class that implements the java.sql.Connection interface.

  1. Connection con=DriverManager.getConnection("jdbc.odbc:rajendra","uname","pwd");
  • here getConnection() call returns the object of Type-1 JDBC DRIVER class. 





Factory Method

Monday 7 June 2010

Example programs for Fast Line Reader or Fast Lane Reader

Fast Line Reader or Fast Lane Reader

Some times applications access data in a tabular fashion, such as when browsing a catalog or a list of names or when exporting data in batches for use elsewhere. This kind of data access is usually read-only. In such situations, using entity beans to represent persistent data incurs(problem) overhead and provides little benefit. Entity beans are best for coarse-grained access to individual business entities, and are not effective for read-only access to large quantities of tabular data.

the fast lane reader design pattern provides a more efficient way to access tabular, read-only data. A fast lane reader component directly accesses persistent data using jdbc components , instead of using entity beans. The result is improved performance and less coding, because the component represents data in a from that is closer to how the data are used.

EJB components &  HIBERNATE persistence logics are called as OR (Object Relational) Mapping persistence logics. Since EJB Components are distrubuted components so their persistence logic can be accessed from remote clients also.

  HIBERNATE is not a distributed technology so its persistence logic can not be accessed from remote clients. To access the  HIBERNATE  logic from remote clients also we need to keep hibernate persistence logic in EJB components like Session Bean component.

Example:

If a java client application takes the support of EJB entity components or Hibernate persistence logic to interact with database software then that process may kill the performance of the application.





Sunday 6 June 2010

Example programs on Fly Weight Design pattern : Student marks list

//Extrinsic.java
package com.demo;

public interface Extrinsic {
String getDivision();

}

//ExtrinsicFactory.java

package com.demo;
import java.util.*;

public class ExtrinsicFactory {
public static Map<String, Extrinsic>m=new HashMap<String,Extrinsic>();
 public static int count;
 //static factorymethod that gives Extrinsic object by checking buffer/cache(m)
public static Extrinsic getExtrinsic(String division)
{
//here Fly Weight logic is implementing
if(m.containsKey(division))
{
Object o=m.get(division);
Extrinsic i=(Extrinsic)o;
return(i);
}
Extrinsic extr=new ExtrinsicFactory.ExtrinsicClass(division);
m.put(division,extr);
return(extr);
}//end of factory method
//inner class acting as Extrinsic class having logic to hold division
public static class ExtrinsicClass implements Extrinsic
{
private String division;
private ExtrinsicClass(String division)
{
this.division=division;
count++;
System.out.println("no.of Extrinsic object="+count);
}
public String getDivision()
{
return(division);
}
}//End of Extrinsic class
}//end of ExtrinsicFactory class

//ICard.java
package com.demo;

public class ICard 
{
//Intrinsic properties
 private String empname;
 private int empid;
 //Extrinsic properties
 private Extrinsic extr;
 public ICard(String empname, int empid, Extrinsic extr)
 {
this.empname=empname;
this.empid=empid;
this.extr=extr;
 
 }
 public void print()
 {
System.out.println("Emp name :"+empname);
System.out.println("Emp id :"+empid);
System.out.println("Division :"+extr.getDivision());
 
 }

}
//MainApp.java
package com.demo;

public class MainApp {
public static void main(String args[])
{
ICard ic1=new ICard("raj",111,ExtrinsicFactory.getExtrinsic("A"));
ICard ic2=new ICard("RAVI",222,ExtrinsicFactory.getExtrinsic("A"));
ICard ic3=new ICard("RAMESH",666,ExtrinsicFactory.getExtrinsic("B"));
ICard ic4=new ICard("RAMANA",999,ExtrinsicFactory.getExtrinsic("A"));
System.out.println("------------");
ic1.print();
System.out.println("------------");
ic2.print();
System.out.println("------------");
ic3.print();
System.out.println("------------");
ic4.print();
}

}
/*
 * output:
 * no.of Extrinsic object=1
no.of Extrinsic object=2
------------
Emp name :raj
Emp id :111
Division :A
------------
Emp name :RAVI
Emp id :222
Division :A
------------
Emp name :RAMESH
Emp id :666
Division :B
------------
Emp name :RAMANA
Emp id :999
Division :A

 */

This Buffer or cache development have Extrinsic Data is nothing but implementation of private Design pattern

Fly Weight Design Pattern

Fly Weight Design Pattern

General meaning of Fly Weight means reducing the weight, here reducing the unnecessary objects.

Definition:

which is used to avoid too many objects of similar types instead try to use the same old object repetively. Create new Object when you really need them.

Fly Weight Design Pattern is used to when there is a need to create high number of objects of almost similar nature. High number of objects consumes (takes) high memory and flyweight design pattern gives a solution to reduce the load on memory by sharing objects. It is achieved by segregating objects properties into two types intrinsic (internal)  and extrinsic (outside or external).

Use sharing to support large numbers of fine-grained objects efficiently". Sharing is key in flyweight pattern and we need to properly decide if this pattern can be applied.

How to Apply Fly Weight Design Pattern:

The object which we are going to create in high number should be analysed before going for Fly Weight Design Pattern. Idea is to create lesser number of objects by reusing the same objects. Create smaller groups of objects and they should be reused by sharing. Closely look at objects properties and they can be segregated as two types intrinsic and extrinsic

Ex:
for ice-cream, brand name is intrinsic. flavor is extrinsic.
for Book, Book name is intrinsic, type of paper, quality of printing is extrinsic,
for Park, visitor name is intrinsic, visitor ticket type is extrinsic



Fly Weight Design PatternExample programs on Fly Weight Design pattern : Student marks list