Anda di halaman 1dari 84

J2EE Design Patterns

Andrew J. Dick
Red Hook Group
andrew@redhookgroup.com
Colorado Software Summit
Design Patterns
?What is a design pattern?
?Can be thought of as a best practice solution to
a common, recurring problem.
?Consists of:
?Name
?Description of problem and its context
?Solution
?Consequences of use
J2EE Design Patterns
?Original patterns described by Gamma et al.
were divided into three categories:
?Creational
?Structural
?Behavorial
?For J2EE, we instead group the patterns
based on the tier they are associated with:
?Data Tier
?Business Tier
?Web Tier
Data Tier Patterns
?Data Access Object (DAO)
What Is a Data Access Object?
?Object that encapsulates access to persistent
storage
?e.g. RDBMS, LDAP, etc.
?Decouples client interface from underlying
data access mechanics
?e.g. Manages connection, adapts APIs
How Does a DAO Work?
?Abstracts the process of managing and
accessing the connection to the data source
?Encapsulates any proprietary APIs
?e.g. Translates lower level exceptions
DAO Relationships

Business Object uses Data Access Object encapsulates Data Source

creates or

obtains or uses

modifies

Transfer Object
DAO Interactions
Business Object Data Source

1: new ()
Data Access Object

2: Get data

3: Get data

4: new ()
Transfer Object
5: return data()

6: Set property

7: Set data

8: Get property

9: Set data
Example DAO - Interface
public interface PersonDao {
/**
* Get a list of all people in the system.
*
* @return List - The list of person summary transfer objects
* @exception DaoException Thrown if a domain error occurs.
*/
List getAllPeople() throws DaoException;

/**
* Creates a new person using the specified Person transfer object.
*
* @param person The transfer object to use as an information source.
* @param userName The user name of the user performing the create command.
* @exception DaoException Thrown if a persistence error occurs.
*/
void createPerson(final PersonInfo person, final String userName)
throws DaoException;

}
Example DAO – Dao
public class MsSqlPersonDao extends BaseDao implements PersonDao {

// Defines the insertion statement.


private static final String INSERT_STATEMENT
= "INSERT INTO person (first_name, middle_names, last_name, "

/**
* Constructs a Person Data Access Object with the specified data source.
*
* @param dataSource The name of the data source.
*/
public MsSqlPersonDao(final String dataSource) {
super(dataSource);
}

}
Example DAO – Factory &
Usage
?Factory method
/**
* Retrieves a Dao responsible for persisting Person related information.
*
* @return PersonDao - The PersonDao to use for persistence
* @exception DaoException Thrown if the DAO cannot be instantiated.
*/
public static PersonDao getPersonDao() throws DaoException {

return new MsSqlPersonDao(getDataSourceName());


}

?Client usage
final PersonDao personDao = DaoFactory.getPersonDao();
DAO Advantages
?Abstracts implementation details
?Data source independent
?Enables easier migration
?Encapsulates proprietary APIs
?Centralizes all data access into a single layer
?Reduces code complexity
Disadvantages of the DAO
?Not useful for CMP EJBs
?Can still be used with the Fast Lane Reader
pattern
?Adds an extra layer to architecture
Why Use a DAO?
?Allows the underlying data access
mechanism to change independently of the
client code
?Allows migration of the data source
?Reduces the code complexity of the business
objects
?Application is easier to manage and maintain
?All data access is centralized into a separate
layer
Business Tier Patterns

?Transfer Object
?Service Locator
?Session Façade
?Business Delegate
?Fast Lane Reader
What Is a Transfer Object?
?A Transfer Object is a data envelope used to
transfer groups of related attributes between
application tiers
?Useful when the client must use RMI to
retrieve and update data
?Not as useful for communication between beans
that can use local interfaces (EJB 2.0)
?Can be used to transfer arbitrary sets of data
(Custom Transfer Object) and entity domain
data (Domain Transfer Object)
How Does a Transfer Object
Work?
?Encapsulates related business data
?Single method call is used to send and
retrieve the Transfer Object
?Business object (EJB or factory) responsible
for constructing Transfer Object
?Passed by value to client via RMI
?Must be serializable
?Immutable and mutable strategies
Transfer Object Relationships
Transfer Object

Creates

Client Business Object

<<EntityEJB>> <<SessionEJB>> Data Access Object


Business Entity Business Session
Transfer Object Interactions
Client Business Object

1: Get data
2: new ()
Server Copy
3: return TransferObject

4: new ()
Client Copy

5: Get value

6: Get value
Example Transfer Object
public class PersonInfo implements Serializable {

// Data fields
private String firstName_ = "";
private String lastName_ = "";

public String getFirstName() {


return firstName_;
}

public void setFirstName(final String firstName) {


firstName_ = firstName;
}


Transfer Object Advantages
?Can simplify remote interface of EJBs
?Reduces number of get and set methods
?Improves performance
?Fewer remote calls
?Reduced network traffic
?Can access arbitrary sets of data specific to
client requirements
What Are the Disadvantages?
?Can introduce stale transfer objects
?Transfer objects can be cached by business
objects and no longer represent current state of
data
?Can increase complexity due to versioning
?Simultaneous updates must be handled
• Last update wins strategy or Version Number strategy
?Requires transaction isolation levels to be
considered
?Inconsistent data could be read if isolation level
less than TRANSACTION-SERIALIZED
Why Use a Transfer Object?
?Each call to an EJB is potentially a remote
call with network overhead
?Client usually requires more than one
attribute of an entity
?e.g. For display purposes
?Accessing each attribute individually
increases network traffic which degrades
performance
What Is a Service Locator?
?Class that abstracts details of looking up and
preparing a service
?EJBs, JMS components, data sources, etc.
?Useful for reducing code complexity of
service clients
?Allows recreation of EJB objects if
connection reestablishment is needed
How Does a Service Locator
Work?
?Usually singleton (per class loader)
?Encapsulates creation of initial context and JNDI
lookup of service objects
• Caching improves performance
?Different strategies
?Type checked
?Properties
Service Locator Relationships
<<Singleton>>
Client uses creates
Service Locator
uses

InitialContext

looks up

uses Service Factory

uses Business Service uses

looks up or creates
Service Locator Interactions
Client ServiceLocator Business Service

1: Get instance
2: new ()
Initial Context

3: Get service
4: Lookup
5: new ()
Service Factory
6: return

7: Get service
8: Create or lookup

9: return service
Example Service Locator
?Class definition
public class ServiceLocator {

private static ServiceLocator locator_ = null;



// Static initializer block
static {
locator_ = new ServiceLocator();
}

private ServiceLocator() {

// Load resource bundle for JNDI lookups


bundle_ = ResourceBundle.getBundle("ServiceLocatorResources");
}

/**
* Retrieves the Singleton instance of the EJB Service Locator.
*
* @return ServiceLocator - The singleton instance of the locator
*/
public static ServiceLocator getInstance() {

return locator_;
}

Example Service Locator
?Retrieval factory method
public EJBHome getHome(final String homeName) throws ServiceLocatorException {

if (homeName == null) {

throw new IllegalArgumentException("homeName is null");


}

// Check if we have already cached the home


if (homeMap_.containsKey(homeName) == false) {
loadHome(homeName);
}

return (EJBHome) homeMap.get(homeName);


}
Example Service Locator
?Usage
final ServiceLocator locator = ServiceLocator.getInstance();
try {
personHome_ = (PersonHome) locator.getHome(PersonHome.class.getName());
}
catch (final ServiceLocatorException serviceLocatorException) {
throw new PersonException(serviceLocatorException);
}
Service Locator Advantages
?Encapsulates complexity of lookup and creation
process
?Uniform service access point for clients
?Easier development overhead
?Improves network performance
?Lookup calls are aggregated on the server
?Improved client performance through caching
?Reduces redundant lookups and object creation
• Initial context
• Service Factories
Why Use a Service Locator?
?Provides a single point of control for Service
Access
?Can improve performance by caching factory
and context objects
?Reduces the code complexity of clients
?Promotes code reuse between multiple
clients
What Is a Session Façade?
?Defines a uniform coarse grained service
access layer
?Hides the complexity of the interaction of
business objects participating in a workflow
?Removes need for client to manage relationships
of these business objects
?Allows consolidation of use cases
How Does a Session Façade
Work?
?Provides a simplified interface for business
services
?Stateless or stateful strategy
?Stateless supports processes that require a
single method call to complete
?Stateful supports processes that require multiple
methods to complete
• e.g. The process requires conversational state
Session Façade Relationships
Client <<SessionEJB>> 1..* Business Object
Session Facade
accesses

<<EntityEJB>> <<SessionEJB>>
Business Entity Business Session

accesses
accesses

Data Access Object


Session Façade Interactions
Client Session Facade Business Session Business Entity Data Access Object

1: Invoke method
2: Invoke method

3: Invoke method

4: Get data

5: return data

6: return result
Example Session Façade
public PersonProfileInfo getPersonProfileForId(final int personId)
throws PersonException {

PersonProfileInfo personProfileInfo = null;


try {
final PersonDao personDao = DaoFactory.getPersonDao();
final RelationshipDao relationshipDao = DaoFactory.getRelationshipDao();
final MarriageDao marriageDao = DaoFactory.getMarriageDao();
personProfileInfo
= new PersonProfileInfo(personDao.getPersonForId(personId));

// Get list of marriages


personProfileInfo.setMarriages(marriageDao.getMarriagesForId(personId));

// Get list of children


personProfileInfo.setChildren(relationshipDao.getChildrenForId(personId));

// Get parents
personProfileInfo.setFather(relationshipDao.getParentForId(personId,
WebConstants.FATHER));
personProfileInfo.setMother(relationshipDao.getParentForId(personId,
WebConstants.MOTHER));
}
catch (final DaoException daoException) {
throw new PersonException("Could not load profile.", daoException);
}
Session Façade Advantages
?Improves performance by reducing network
overhead
?Introduces control layer for business tier
?Centralizes security management and
transaction control
?Reduces coupling of tiers
?Exposes uniform interface for interaction
?Coarse grained access to business services
?Exposes fewer remote interfaces to clients
Why Use a Session Facade?
?Enforces execution of the use case in a
single network call
?Provides a clear layer to encapsulate
business and workflow logic used to fulfill
use cases
?With EJB 2.0, session façade can use local
interfaces to avoid network overhead
What Is a Business Delegate?
?Object that decouples the presentation tier
and business services tier
?Abstracts the underlying implementation
details of the business services
?Provides domain level access point for
different clients in the presentation tier to
access the business services
How Does a Business
Delegate Work?
?Encapsulates the lookup and access details
of the business services
?e.g. EJB access details (home, remote creation
and lookup)
?Handles exceptions from the services layer
and translates them to business exceptions
?Transparently performs any retry or recovery
operations if a service fails
Business Delegate
Relationships

Client Business Delegate Uses Business Service

Looks up
or creates
Lookup Service
Business Delegate Interactions
Client Lookup Business
Service Service
1: new () Business
Delegate

2: Get service

3: Lookup

4: Return Business Service

5: Invoke

6: Invoke
Example Business Delegate
public int createPerson(final PersonInfo personInfo) throws PersonException {

try {
final ServiceLocator locator = ServiceLocator.getInstance();
PersonHome personHome
= (PersonHome) locator.getHome(PersonHome.class.getName());
final Person person = personHome.create();
return person.createPerson(personInfo);
}
catch (final ServiceLocatorException serviceLocatorException) {
throw new PersonException(serviceLocatorException);
}
catch (final EJBException ejbException) {
throw new PersonException("Could not create person.",
ejbException);
}
catch (final CreateException createException) {
throw new PersonException(“Problem creating person session.",
createException);
}
catch (final RemoteException remoteException) {
throw new PersonException(remoteException);
}
}
Business Delegate Advantages
?Reduces coupling between tiers
?Translates business services exceptions
?e.g. Network and infrastructure exceptions
translated to business exceptions
?Provides a uniform interface to the business
tier
?Supports failure recovery
?Can improve performance through caching
What Are the Disadvantages?
?Introduces an additional layer of abstraction
?Small amount of additional upfront work; but
has considerable long term benefits
?Location transparency can hide remoteness
from developers
Why Use a Business Delegate?
?Allows different clients (devices, web, thick client)
to uniformly access business services
?Decouples presentation tier from business tier
?Can minimize impact of business services API changes
on presentation tier
?Hides underlying implementation details of services
such as lookup and access
?Can perform caching of service information
?Can act as an adapter between disparate systems
in a B2B system
What Is a Fast Lane Reader?
?Best practice that bypasses the entity bean
layer for batch reads
?Useful if lists of read only data are required
?e.g. For tabular display to the user
How Does a Fast Lane Reader
Work?
?Used behind a Session Façade or View
Helper
?Uses a DAO to read a batch of entity data
directly from the data source
?Allows complex queries to be performed
?Avoids overhead of accessing large quantities of
tabular data through the entity layer
Fast Lane Reader
Relationships

Client <<SessionEJB>> Data Access Object Encapsulates Data Source


Uses
Business Session

Obtains Creates

Transfer Object
Fast Lane Reader Interactions
Client Business Session Data Source

1: Query

2: new ()
Data Access Object

3: Get data

4: Get data

5: new ()
Transfer Object
6: return list
Example Fast Lane Reader
public List getAllPeople() throws PersonException {

List peopleList = null;


try {
final PersonDao personDao = DaoFactory.getPersonDao();
peopleList = personDao.getAllPeople();
}
catch (final DaoException daoException) {
throw new PersonException("Could not load list of people.",
daoException);
}

return peopleList;
}
Fast Lane Reader Advantages
?Entity beans are best for coarse grained access to
individual business entities
?Using the entity layer to read N entities would require N
+ 1 calls
• For BMP and some CMP implementations
?No transactional overhead for simple queries
?Reads can be performed without transactions allowing
lightweight reads
?Uses any DB caching functionality
?Database can cache the larger multi-table query
?Retrieves only the data required
?Allows extraction of only columns needed for display
What Are the Disadvantages?
?Tightens coupling between business and
persistence logic
?Session bean now aware of underlying
persistence mechanism
?Less maintainable (moves logic that is more
susceptible to flaws into the business tier)
?Database schema changes impact multiple code
regions
?Potential for stale data
?Bypasses concurrency layer provided by entities
Why Use a Fast Lane Reader?
?Allows complex queries to be performed with
a single bulk read
?In contrast to the N + 1 calls required through
the entity layer
?If EJB 1.x used, each of these calls would
require overhead of a remote call
?Using the entity layer is difficult if joins are
required
?Traversal of relationship graph can be complex
Web Tier Patterns
?View Helper
?Composite View
?Front Controller
What Is a View Helper?
?Class that performs data retrieval for the
view
?Extracts business data logic into a separate
class
?Useful when one view is commonly used to
handle a specific business request
?e.g. Displaying a summary view
?Can help separate team development roles
?e.g. Software development and Web production
How Does a View Helper
Work?
?View helper retrieves and stores view’s
intermediate data model
?Serves as a business data adapter
?View delegates these processing
responsibilities to View Helper
?e.g. Custom tag library or Java Bean strategy
?Encapsulates business processing from View
components
?View is responsible for formatting and
presentation logic
View Helper Relationships

Client 1..* View 0..* Helper


View Helper Interactions
Client View Helper Value Bean Business Service

1: Request
2: Get data

3: Get data

4: Get property
Example View Helper - Usage
<logic:iterate id="summary“ name="search.results.key">
<row:row oddColour="white" evenColour="silver">
<td>
<html:link forward="edit.person"
paramId="selected.person.key"
paramName="summary"
paramProperty="personId">
<bean:write name="summary" property="firstName"/>
<bean:write name="summary" property="middleNames"/>
<bean:write name="summary" property="lastName"/>

</html:link>
</td>
</row:row>
</logic:iterate>
Example View Helper - Result
View Helper Advantages
?Improves maintainability by providing clearer
separation of view from business processing
?Better code reuse
?Less bugs as custom tags are inherently easier
to test than scriptlets
?Improves better role separation for
development staff
?JSP + tag library use – web designer
?View Helper implementation - developer
What Are the Disadvantages?
?More upfront work to develop custom tags
?Many tag libraries already exist though
?Extra configuration work to use tag libraries
Why Use a View Helper?
?Promotes better component reuse
?Application design is more modular and
easier to maintain
?Easier to test logic in a View Helper than in
the View
?Allows different team members to focus on
their specialties
What Is a Composite View?
?Aggregate view built using other reusable
sub-views
?Each sub-view may be atomic or itself a
composite view
?Change to a sub-view is automatically reflected
in every composite view using it
?Each component can be dynamically
included into the display
How Does a Composite View
Work?
?Modular atomic views are created
?Templates used to control layout of
fragments independent of content
?Atomic views can be included at either
translation time (Early Binding) or runtime
(Late Binding)
?Early Binding faster but view remains static until
JSP recompiled
Composite View Relationships

Basic View

View Composite View


Composite View Interactions
Composite View View Manager Header View Footer View

1: Include
2: Include

3: Include

4: Include
Example Composite View
? Example template
<table>
<tr>
<td colspan="2">
<template:get name='header'/>
</td>
</tr>
<tr>
<td width=“150px”>
<template:get name='sidebar'/>
</td>
<td>
<template:get name='content'/>
</td>
</tr>
<tr>
<td colspan="2">
<template:get name=‘footer'/>
</td>
</tr>
Example Composite View
? Example template usage
<%@ taglib uri='/WEB-INF/tlds/struts-template.tld'
prefix='template‘ %>

<template:insert template='/common/template.jsp'>
<template:put name='header' content='/common/header.jsp' />
<template:put name='sidebar' content='/common/sidenav.jsp' />
<template:put name='content'
content='/person/welcome-content.jsp'/>
<template:put name='footer' content='/common/footer.jsp' />
</template:insert>
Example Composite View
Composite View Advantages
?Better modularity
?Each fragment does its job
?Increased reuse
?Fragments can be reused in different views
?Views have enhanced flexibility
?Can be constructed to suit each viewer’s access
rights
?Individual components are easier to manage
?Can update fragments without effecting layout
What Are the Disadvantages?
?Reduces manageability
?Valid subviews do not ensure valid composite
• e.g. subviews with <html> and </html> tags.
?Performance reduction
?Generation of numerous subviews may slow
performance
Why Use a Composite View?
?Promotes code reuse
?Simplifies layout changes
?Simplifies development
?Allow easy prototyping of website layout with
static content placeholders
What Is a Front Controller?
?Single component that provides an initial
point of contact for handling application
requests
?Centralizes common application functions
• View selection
• Security
• Templates
?Reduces embedded system service code
(which is often duplicated in each view)
?Views are simplified
How Does a Front Controller
Work?
?Manages handling of application requests
?Invoking security services
?Delegating business processes
?View navigation
?Error handling
• Often coordinates with dispatcher and view helper
components
?Can use multiple controller instances to
avoid creating a single point of failure
Front Controller Interactions
Client Controller Dispatcher View Helper

1: Send request
2: Delegate request
3: Forward request

4: Send request
5: Forward request

6: Send request
7: Process request
Example Front Controller
?Segment of Struts ActionServlet request
processing
? * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
reserved

protected void process(HttpServletRequest request,


HttpServletResponse response)


// Acquire the Action instance to process this request
Action actionInstance = processActionCreate(mapping, request);

ActionForward forward
= processActionPerform(actionInstance, mapping,
formInstance, request, response);

processActionForward(forward, mapping, formInstance,
request, response);
Front Controller Advantages
?Provides a central place to handle system
services and business logic across multiple
requests
?Encourages reuse
?Centralizes control providing a choke point
for illicit access
?Promotes cleaner application partitioning
?Reduces code duplication
Why Use a Front Controller?
?Common business logic can be handled in
one location rather than replicated in
numerous views
?Provides a centralized point of contact which
allows control and logging of a user’s
progress through a site
?Removes common system functionality from
the view
Patterns We Talked About
?Data Tier ?Business Tier
?Data Access Object ?Transfer Object
?Web Tier ?Service Locator
?View Helper ?Session Façade
?Composite View ?Business Delegate
?Front Controller ?Fast Lane Reader
Resources
?Core J2EE Patterns: Best Practices and Design
Strategies
by Deepak Alur et al., Prentice Hall PTR
ISBN: 0-13064-884-1
?EJB Design Patterns: Advanced Patterns,
Processes, and Idioms
by Floyd Marinescu, John Wiley & Sons
ISBN: 0471208310
?Design Patterns: Elements of Reusable Object-
Oriented Software
by Eric Gamma et al., Addison Wesley Professional
ISBN: 0201633612
Websites
? http://java.sun.com/blueprints/corej2eepatterns
? http://www.theserverside.com/patterns

? Sample app can be found at:


? http://www.redhookgroup.com/downloads/css/genealogy.zip

?Thank you.

?Any questions
?andrew@redhookgroup.com

Anda mungkin juga menyukai