Friday, April 13, 2007

Design Patterns in Java/J2EE

What is the design Pattern?

If a problem occurs over and over again, a solution to that problem has been used effectively.
That solution is described as a pattern. The design patterns are language-independent strategies for solving common object-oriented design problems .

Type of design patterns

Creational Patterns
Structural Patterns
Behavioral Patterns
J2EE Patterns

Creational Patterns

Abstract Factory
Builder
Factory Method
Prototype
Singleton

Factory Method

Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated , based on the conditions or parameters given.

Where to use & benefits

A class wants its subclasses to specify the object.
A class cannot anticipate its subclasses, which must be created.
A family of objects needs to be separated by using shared interface.
The code needs to deal with interface, not implemented classes.
Factory methods can be parameterized.
The returned object may be either abstract or concrete object.
Hide concrete classes from the client.

Abstract Factory

Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated , based on the conditions or parameters given.

Where to use & benefits

A class wants its subclasses to specify the object.
A class cannot anticipate its subclasses, which must be created.
A family of objects needs to be separated by using shared interface.
The code needs to deal with interface, not implemented classes.
Hide concrete classes from the client.
Factory methods can be parameterized.
The returned object may be either abstract or concrete object.


Ex of Factory method

To paint a picture, you may need several steps. A shape is an interface.
Several implementing classes may be designed in the following way.



interface Shape {
public void draw(); }
class Line implements Shape { Point x, y; Line(Point a, Point b)
{ x = a; y = b; }

public void draw()
{ //draw a line; } } class Square implements Shape
{ Point start; int width, height; Square(Point s,
int w, int h) { start = s; width = w; height = h; }

public void draw()

{ //draw a square; } }

class Circle implements Shape { .... }

class Painting
{
Point x, y; int width, height, radius;
Painting(Point a, Point b, int w, int h, int r)
{
x = a; y = b; width = w; height = h; radius = r;
}

Shape drawLine()
{
return new Line(x,y);
}

Shape drawSquare()
{
return new Square(x, width, height);
}
Shape drawCircle()
{
return new Circle(x, radius);
}

.... }

... Shape pic; Painting pt;

//initializing pt .... if (line) pic = pt.drawLine();


if (square) pic = pt.drawSquare(); if (circle) pic = pt.drawCircle();


From the above example, you may see that the Shape pic's type depends on the condition given. The variable pic may be a line or square or a circle.

Singleton

One instance of a class or one value accessible globally in an application
Ensure a class has only one instance and provide a global point of access to it.

Where to use & benefits

Ensure unique instance by defining class final to prevent cloning.
May be extensible by the subclass by defining subclass final.
Make a method or a variable public or/and static.
Access to the instance by the way you provided.
Well control the instantiation of a class.
Define one value shared by all instances by making it static.
Related patterns include



Ex of Singleton method

For example, to make a unique remote connection,




final class RemoteConnection

{
private Connect con;

private static RemoteConnection rc = new RemoteConnection(connection);

private RemoteConne

ction(Connect c)



For example, to make a unique remote connection,

final class RemoteConnection

{
private Connect con;

private static RemoteConnection rc = new RemoteConnection(connection);

private RemoteConne

ction(Connect c)

usage: RemoteConnection rconn = RemoteConnection.getRemoteConnection; rconn.loadData(); ... The following statement may fail because of the private constructor RemoteConnection con = new RemoteConnection(connection); //failed //failed because you cannot subclass it (final class) class Connection extends RemoteConnection {} For example, to use a static variable to control the instance;

public static void main(String [] args) { try { Connection con = new Connection(); //ok }catch(Exception e)

{
System.out.println("first: " +e.getMessage()); }

try { Connection con2 = Connection.getConnection();

//failed. }catch(Exception e)

{

System.out.println("second: " +e.getMessage());

} } }






Structural Patterns

Adapter
Bridge
Composite
Decorator
Façade
Flyweight
Proxy


Adapter
Convert the existing interfaces to a new interface to achieve compatibility and reusability of the unrelated classes in one application. Also known as Wrapper pattern.

Where to use & benefits

Make unrelated classes work together.
Multiple compatibility.
Increase transparency of classes.
Make a pluggable kit.
Delegate objects.
Highly class reusable

Example


import javax.swing.*;

import java.awt.event.*;

class Test extends JFrame

{

public Test ()

{ setSize(200,200);

setVisible(true);



addWindowListener(new Closer()); } public static void main(String[] args) { new Test(); }

class Closer extends WindowAdapter { public void windowClosing(WindowEvent e)

{ System.exit(0); } } }




Facade

Make a complex system simpler by providing a unified or general interface, which is a higher layer to these subsystems

Where to use & benefits

Want to reduce complexities of a system.
Decouple subsystems , reduce its dependency, and improve portability.
Make an entry point to your subsystems.
Minimize the communication and dependency between subsystems.
Security and performance consideration.
Shield clients from subsystem components.
Simplify generosity to specification.
Related patterns include

Ex of facade


interface General

{

public void accessGeneral();

}

interface Special extends General

{

public void accessSpecial();

}

interface Private extends General

{

public void accessPrivate();

}





interface Private extends General { public void accessPrivate();

}

class GeneralInfo implements General {

public void accessGeneral() { //... } //...



class GeneralInfo implements General {

public void accessGeneral()

{ //... } //... }

class SpecialInfo extends GeneralInfo implements Special

{ public void accessSpecial()

{ //... } }

class PrivateInfo extends SpecialInfo implements Private

{ public void accessPrivate()

{ // ... } //... }

class SpecialInfo extends GeneralInfo implements Special

{

public void accessSpecial()

{ //... } } class PrivateInfo extends SpecialInfo implements Private { public void accessPrivate() { // ... } //... }



J2EE Patterns

MVC
Intercepting Filter
View Helper
Front Controller
Composite View

Service Locator
Transfer Object
Composite Entity
Data Access Object
Session Facade
Business Delegate

MVC

The Model/View/Controller
(MVC) is an architecture design pattern. Model means data, View means representation and Controller works on data and representation. MVC focuses on decouple the triad relationships among data, representation and controller

Where to use & benifits

Application architecture design.
Any data related design, including non-visual application.
Decouple complex object to improve maintainability.
Increase object reusability.
Achieve design flexibility.
Related patterns include
Almost all patterns can be used with MVC.


Core Issue

MVC consists of three kind of objects. The Model is an internal representation of the data, the View is the screen presentation of GUI, and the Controller coordinates changes between the Model and View.

Theory of MVC Design Pattern

To achieve the MVC architecture in your project, you have to decouple View and Model by Controller. Your GUI as View should be designed as a module. It can be launched separately.
Your data related classes as Model should be treated as a module too. Your controller classes should response to any data change on the GUI. Such design will increase reusability and flexibility.

Try to visualize that the user reacts with the GUI, a DataManager(Controller) listens to the GUI's call. If the user needs to load data, such request is sent to the DataManager, the DataManager starts loading
searching and extracting the requested data from the server and sends it back to the GUI. GUI is responsible to display data.
Here the server acts as Model, the DataManager acts as Controller and GUI acts as View. The DataManager can be used for both remote and local modes

the GUI can be replaced with any design and the data related classes can be packaged together and put on local and server sides. All of the three objects can be reused for other projects with little code alteration


Interception Filter


A pluggable component design to intercept incomming requests and outgoing responses, provide common services in a standard manner (independently) without changing core processing code.

Where to use & benefits

Logging and authentication.
Enhance security.
Add additional function to existing web application.
Decorate main process.
Debug.
Pre-processing or post-processing for specific clients.
Uncompress incoming request.



Front Controller

Using a single component to process application requests

Where to Use & benifits
JSP or Servlet.
Design request handling component.
Channel all requests through a single controller.
Centralize request processing and view selection.
Reduce business logic in a view
Improve manageability of security
Promote code reuse across requests


Composite View
Use a coarse-grained interface to manage interactions between fine-grained or coarse-grained and dependent objects internally. The Composite Entity is a coarse-grained entity bean. It may be the coarse-grained object or hold a reference to the coarse-grained object. Also known as Aggregate Entity.

Where to Use & benifits

Improve manageability by reducing entity beans.
Improve network performance
Reduce database schema dependency
Increase object granularity
Facilitate composite transer object creation.

Important Links

http://java.sun.com/blueprints/patterns/catalog.html
http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html
http://gee.cs.oswego.edu/dl/cpj/ifc.html
http://www.javacamp.org/designPattern/
http://www.fluffycat.com/java-design-patterns/
http://www.patterndepot.com/put/8/JavaPatterns.htm

No comments: