J2EE Patterns
Slides by Igor Polevoy
October 30 2003
Pattern Definition
• Pattern is a best practice solution to a
common recurring problem
• Pattern describes a recurring problem
• Pattern describes a typical solution to the
problem
• Patterns are collective knowledge
• Patterns are great vehicle to share
knowledge with more people
Pattern Benefits
• Provides a high level language for design
discussions
• Provides a well tested solution for a
common problem
• Helps provide some design work
• Combinations of patterns tend to provide
for reusable architecture frameworks
Pattern History
• Christopher Alexander: A Pattern
Language 1977
• Gamma, etc (Gang of Four, GoF): Design
Patterns: Elements of Reusable Object-
Oriented Software 1994
GoF Pattern Categories
• Creational
– Singleton
– Abstract Factory
• Structural
– Decorator
– Adapter
• Behavioral
– Strategy
– Chain of Responsibility
EJB Layer Patterns
• Session Façade
• Message Façade
• EJB Command
• Data Object Transfer Factory
• Generic Attribute Access
• Business Interface
Example of J2EE Application
Fine-Grained Access
Disadvantages
• Increased network overhead
• Client needs to have intimate knowledge of server side
components
• Data access, business and workflow logic scattered
across client
• Tight coupling of clients and server components
• Transaction not managed, funds can be in the undefined
state
• Poor people role separation
• Poor maintainability
• Poor reusability
Fine-Grained Access Solutions
– Encapsulate all logic inside entity beans, have
client make just one call
• Disadvantages: tight coupling of business logic and
data, lower level of component reuse
– Transaction demarcation handled by client
• If client is far away, transactions will run for long
time, reducing overall performance of system
• Client needlessly complex
• Solves only data integrity problem
Session Façade Pattern
• Façade Pattern (GoF) provides a unified
interface to a set of interfaces in a subsystem.
Façade provides a higher-level interface that
makes it the sub-system easier to use
• Session Façade Pattern applied to J2EE only
• Session Façade provides a layer of abstraction
to subsystem of session beans, entity beans and
other components
• Hides server component complexity from client
Session Façade Pattern
• Implemented as a layer of stateless beans
(sometimes statefull)
• Provides a clean interface to execute
business logic and workflow
• Separates complexity from client
• Provides for automatic transaction support
• Separates development roles
• From OO point of view provides for layer of
abstraction and encapsulation
Session Façade Pattern
• Before
Session Façade Pattern
• After:
Session Façade Pattern
• Solution:
Session Facade
• Benefits:
– Lower network overhead
– Separation of business logic from
presentation
– Inherent transaction support
– Promotes reusability
– Looser coupling
Session Facade Dangers
• Do not create a God Session Façade
• Do not put presentation logic into façade
• Do not use Session Façade as domain
model, use it only as glue
Situation in Enterprise
• Need to execute a number of session and
entity beans in a context of the same
transaction
• Immediate response is not required
• Client does not have to be required to wait
end of execution
Situation in Enterprise
Solutions
• Use Session Façade Pattern
– Solves the following problems:
• Coupling
• Performance
• Maintainability
• Data integrity
– Does not solve:
• Response time
• Reliability
Message Façade Pattern
Message Façade Pattern
• Use a Message Driven Bean to create a
reliable fault-tolerant façade
• Client should only send messages to JMS
destination. They should not access
session and entity beans directly
Message Façade Pattern
• Solves:
– Response time
• Inherently by use of messaging
– Reliability
• If a transaction fails, then the MDB can push the
message back into destination; the message will
be re-delivered
Message Façade Pattern
• Usage:
– Do not put business logic into MDB
– Use Message Façade pattern together with
Session Façade Pattern
• Disadvantages:
– Propagate results back to client
– Cannot perform compile time type checking
Command Design Pattern (GoF)
• Used to encapsulate executable logic in
command units
• Decouples application client component
from domain model
• Used to provide undo/redo functionality
EJB Command Pattern
• Goal: to decouple application client
component from binding to concrete
domain model objects
• Separate development roles in projects
• Simplify access to Session Façade
• Use command beans with set/get methods
and execute method
EJB Command Pattern
EJB Command Pattern
• Elements:
– Command Beans
– Client side routing logic
– Command server
EJB Command Pattern
• Benefits:
– Easier to deploy the application (fewer
session beans)
– Separates business logic from presentation
– Decouples application client component from
EJBs
– Command can execute locally, produce fake
data to facilitate independent development
EJB Command Pattern
• Disadvantages
– Primitive transaction control (limited by
command server)
– Commands are stateless – no easy way to
access statefull beans
– Limited exception handling mechanism
– Command beans classes loaded into J2EE
runtime – no easy way to change functionality
on the fly
Data Transfer Object Pattern
Data Transfer Object Pattern
DTO Factory Pattern
• Problem with DTO:
– DTOs change very often
– Entity beans need to be updated
– DTO consumption is unclear
– Business domain logic creeps into entity
beans
• Solution:
– Place responsibility for creation/consumption
of DTOs onto DTO Factories
DTO Factory Pattern
• DTO Factory Pattern can be implemented
as:
– Simple java class
– Session bean
DTO Factory Pattern
DTO Factory Pattern
• Benefits:
– Changes in creation of DTOs are performed in DTO Factories,
making entity beans more stable
– DTO Factory can create different views of the same data
– DTO Factory can create complex composite DTOs, which hold
data from multiple entity beans
– DTO Factory can provide consumption of DTOs:
• Application client will create a DTO, will set all necessary attributes,
it will then pass it to DTOFactory.setXXXDTO() – this will cause the
factory to find appropriate entity beans ad call their respective set
methods all in the context of one transaction
– Multiple applications can reuse the same persistence layer as
long as they provide DTO Factories with appropriate logic
DTO Factory Usage
DTO Factory Pattern Problems
• Does not scale well with attribute number
growth
• Entity bean clients are tightly coupled with
entity bean interfaces
• Solution: Generic Attribute Access Pattern
Generic Attribute Access Pattern
• Move attribute access logic from entity
bean client to a generic attribute access
class
• This class will provide access to attributes
via Maps of attribute keys and their
respective values
Generic Attribute Access Pattern
• Attribute access is built into entity beans as
implementation of AttributeAccess interface
• Such interface would be implemented by a
remote or local interface and the beans itself
interface AttributeAccess
{
void setAttributes(Map attributes);
Map getAttributes();//gets all attributes
Map getAttributes(Set keys);//gets some attributes
}
Generic Attribute Access Pattern
Generic Attribute Access Pattern
• Benefits:
– A BMP can hold it’s state in a Map, simplifying the
GAA implementation
– No need to program DTOs
– Attribute access code can be shared by all beans in
the system – simplicity
– In CMP, Java Reflection API can be used for updates
– same code can be shared between all CMPs in the
system (use a super class)
– Scales well for large number of attributes/beans
– One attribute access interface across all beans
– Allows for creation of generic clients
Generic Attribute Access Pattern
• Tradeoffs:
– Additional overhead: need to construct an
attribute access call, need to cast the attribute
value
– Need to maintain attribute contract
– No compile-time type checking
Generic Attribute Access Pattern
• Recommendations:
– Provide a well documented contract for attribute naming
conventions
– Use Java Beans design patterns for naming conventions
– Can se static finals on bean classes for run time name checking
– Can use a shared interface that serves as a name binding
contract:
Interface PersonBeanNames
{
public static final String firstName;
public static final String lastName;
public static final String ssn;
. . .
}
Business Interface Pattern
• Create a business interface for a bean
• Extend it in the remote/local interface
• Implement it in the bean class
Data Transfer RowSet Pattern
• Transfer relational data in a tabular format
to client application
• If use DTOs you convert tabular data to
OO (EJB), then back to tabular (HTML)
• Use JDBC + RowSet to transfer tabular
data directly to client
Data Transfer RowSet Pattern
• Advantages:
– Can use the same generic client code to process all
tabular requests
– Can use GUI automation (automatic rendering of
ResultSet)
• Tradeoffs:
– No compile time checking
– Not OO
– Client may need to know DB structure (can be
remedied by Session Facade Pattern)
Version Number Pattern
• Problem:
– Data read is performed in a different
transaction then data update
– Hence – danger of update on stale data
– Difficult to wrap read/write into the same
transaction because of “think time”
– Data collision can happen
Version Number Pattern
• Solution:
– Use record (bean) version number
– Include version number into the cross tier
transmission
– Send version number back for update along
with any changed attributes
– Before update, validate version number
– Reject update if stale record is updated
– When update happen, increment version
number
Version Number Pattern
• Implementation
– Depends on inter-tier transmission pattern
– Have legacy applications update data through
J2EE persistence layer; if impossible, write
DB triggers that update version numbers
JDBC For Reading
or
Fast Lane Reader Pattern
• Problems accessing entity beans for
reading:
– N+1 DB read problem
– Network overhead for multiple calls
– Join operations are difficult
JDBC For Reading Pattern
• Solution:
– Use straight JDBC for read operations
– Use CMPs for update operations
– Use in conjunction with other patterns
• Benefits:
– No transaction dependency
– DBMS cache mechanism used
– Simple to join data
• Tradeoffs:
– Bug prone
– No compile time type checking
– Tight coupling of client and persistence layers
Data Access Command Bean
Pattern
• Without DACB, session beans access
entity beans and JDBC directly
• Problems:
– Tight coupling between session layer and
persistence implementation
– Data access logic mixed in with business logic
– Session bean layer is dependent on schema
changes
– High potential for copy/paste style code reuse
Data Access Command Bean
Pattern
• Encapsulate persistence logic into Bean
Command classes
• Bean Command interfaces provide a layer of
abstraction from concrete implementation of
persistence layer
• Similar to EJB Command Pattern
• Differences from EJB Command Pattern:
– DACB provides transparent interface to EJBs, JDBC,
ObjectStore, etc (as opposed to session bean layer)
– Serves as insulation layer between Session Beans
(facade) and concrete persistence implementation
– Semantically models data closer
Data Access Command Bean
Pattern
Data Access Command Bean
Pattern
Data Access Command Bean
Pattern
Data Access Command Bean
Pattern
• Benefits:
– Provides a clean abstraction layer for data
store
– Usable in any tier
– Decouples business logic from storage logic
– Facilitates independent development if
dummy commands are used
• Disadvantages:
– Extra work for developers
EJBHomeFactory Pattern
(Service Locator Pattern)
• Problems:
– Client has repetitive code for lookups of home
interfaces
– Each time the lookup is done, a potential
network call is performed
EJBHomeFactory Pattern
• Solution:
– Provide a factory class, which encapsulates
all of the lookup code, and potentially caches
home interfaces
– Usually implemented as Singleton
Example:
Account acc =
BusinesInterfaceFactory.getInstance().getInterf
ace(com.acme.Account.class);
All of the factory parameters for JNDI lookups
are stored in the configuration of a factory.
EJBHomeFactory Pattern
• Can be used in conjunction with Abstract
Factory Pattern to make creation of
business interfaces completely transparent
to client code
Business Delegate Pattern
• Problem:
– When client uses a session façade or other interface
to J2EE logic, there is a tight coupling between
application client components and EJBs
– Programming directly to EJB layer in not the best way
• Clients need to be aware and handle transaction J2EE
exceptions
• Complicates client logic with EJB exception handling
• Couples client directly to EJB or JMS (message facade) APIs
Business Delegate Pattern
• Solution:
– Create a layer of abstraction that insulates
application client components from handling
service discovery, complex exception
handling and recovery
– A Business Delegate is a plain Java class that
usually maps to session façade one – to one
Business Delegate Responsibilities
• Delegate requests to session façade or
message façade
• Hide EJB API exceptions behind application
level exceptions
• May cache data locally
• May retry failed requests transparently to client
• Assists in large projects if dummy business
delegates are used to asynchronously develop
client and server functionality
Pattern Categories
• EJB Layer
– Session Façade
– Message Façade
– EJB Command
– Data Transfer Object Factory
– Generic Attribute Access
– Business Interface
• Inter-tier data transfer
– DTO
– Data Transfer HashMap
– Data Transfer RowSet
• Transaction/persistence
– Version Number
– JDBC for Reading
– Data Access Command Bean
– Dual Persistence Entity Bean (CMP/BMP)
• Client-side EJB Interaction
– EJB Home Factory
– Business Delegate