Design Patterns J2EE

42
Best Practices and Design Strategies J2EE Design Patterns

Transcript of Design Patterns J2EE

Page 1: Design Patterns J2EE

Best Practices and Design StrategiesJ2EE Design Patterns

Page 2: Design Patterns J2EE

13 March 2009

Contents • J2EE Overview• Three Tier Architecture• Design Pattern Overview• Design patterns

Intercepting FilterFront ControllerApplication ControllerContext ObjectTransfer ObjectBusiness DelegateService LocatorData Access ObjectSession Façade

Page 3: Design Patterns J2EE

13 March 2009

J2EE Overview• J2EE is a platform for developing distributed enterprise software applications.

• The J2EE Platform offers numerous advantages to the enterprise:

• J2EE establishes standards for areas of enterprise computing needs suchas database connectivity, enterprise business components, message-orientedmiddleware (MOM), Web-related components, communicationprotocols, and interoperability.

• J2EE promotes best-of-breed implementations based on open standards,protecting technological investment.

• J2EE provides a standard platform for building software components thatare portable across vendor implementations, avoiding vendor lock-in.

Page 4: Design Patterns J2EE

13 March 2009

• J2EE decreases time to market because much of the infrastructure andplumbing is provided by the vendors’ products, which are implementedaccording to the standard J2EE specification. IT organizations can nowget out of the middleware business and concentrate on building applicationsfor their business.

• J2EE increases programmer productivity, because Java programmers canrelatively easily learn J2EE technologies based on the Java language. Allenterprise software development can be accomplished under the J2EEplatform, using Java as the programming language.

• J2EE promotes interoperability within existing heterogeneous environments.

Page 5: Design Patterns J2EE

13 March 2009

Three Tier Architecture

J2EE platform (and application) is a multitier system, we view the system in terms of tiers. A tier is a logical partition of the separation of concerns in the system. Each tier is assigned its unique responsibility in the system. We view each tier as logically separated from one another. Each tier is loosely coupled with the adjacent tier. We represent the whole system as a stack of tiers.

Page 6: Design Patterns J2EE

13 March 2009

• Presentation Tier

This tier encapsulates all presentation logic required to service the clients thataccess the system. The presentation tier intercepts the client requests, providessingle sign-on, conducts session management, controls access to business services,constructs the responses, and delivers the responses to the client. Servletsand JSP reside in this tier.

• Business Tier

This tier provides the business services required by the application clients. Thetier contains the business data and business logic. Typically, most business processingfor the application is centralized into this tier.

• Integration Tier

This tier is responsible for communicating with external resources and systems such asdata stores and legacy applications. The components in this tier can use JDBC, J2EE connector technology, or some proprietary middleware to work with the resource tier.

Page 7: Design Patterns J2EE

13 March 2009

Design Pattern OverviewPatterns are about communicating problems and solutions. Simply put, patternsenable us to document a known recurring problem and its solution in a particularcontext, and to communicate this knowledge to others.

The patterns presented here extract these “best practice” approaches andpresent them to you in a way that enables you to apply the patterns to your ownparticular application and to accommodate your own needs. The patterns clearlyand simply express proven techniques. They make it easier for you to reuse successfuldesigns and architectures. Simply put, you can use the patterns to designyour J2EE system successfully and quickly.

Page 8: Design Patterns J2EE

13 March 2009

Design patterns A pattern is an idea that has been useful in one practical context and will probably be useful in others.

• 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

Page 9: Design Patterns J2EE

13 March 2009

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

Page 10: Design Patterns J2EE

13 March 2009

EJB Layer Patterns• Intercepting Filter• Front Controller• Application Controller• Context Object• Transfer Object• Business Delegate• Service Locator• Data Access Object• Session Façade

Page 11: Design Patterns J2EE

13 March 2009

Intercepting Filter• Activities or tasks which are common for each request will be performed in this filter class.

• Use an Intercepting Filter as a pluggable filter to pre and post process requests and response.

• A filter manager combines loosely coupled filter in a chain , delegating the control to appropriate filter.

• In this way , you can add, remove , and combine these filters in various way without changing existing code.

Filters are controlled declaratively using a deployment descriptor. A deployment configuration files set up a chain of filters and can include a mapping of specific URLs to the filter chain.

Page 12: Design Patterns J2EE

13 March 2009

Sequence diagram

Page 13: Design Patterns J2EE

13 March 2009

Implementation of FilterTo implement a filter for your web application, you need to do two things

1.The first is to write a class that implements the Filter interface.

2.Modify the deployment descriptor to tell the container when to call filter.

Filter Contains three interfaces: Filter,Filterchain and FilterConfig.

If you look at the filter interface, you can see that when a filter’s doFilter() method is called ,one of the arguments passed is a reference to a FilterChain.when the filter calls chain.doFilter(), the next filter in the chain is called if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.

Page 14: Design Patterns J2EE

13 March 2009

Two tags within the deployment descriptor describe the filters and indicate to which servlet requests the filter should be applied.

<filter><filter-name>AuthFilter</filter-name><filter-class>com.common.filter.AuthFilter</filter-class>

</filter><filter-mapping>

<filter-name>AuthFilter</filter-name><url-pattern>*.do</url-pattern>

</filter-mapping><filter>

<filter-name>WebFilter</filter-name><filter-class>com.common.filter.WebFilter</filter-class>

</filter> <filter-mapping>

<filter-name>WebFilter</filter-name><url-pattern>*.do</url-pattern>

</filter-mapping>• The filters are applied in the same order that the <filter-mapping> element appear in the

deployment descriptor

Page 15: Design Patterns J2EE

13 March 2009

Front Controller

A Front Controller is the initial point of contact for handling all related requests. The Front Controller centralizes control logic and manages the key request handling activities.

A front Controller typically uses an application controller, which is responsible for action and view management.

• Action management refers to locating and routing to the specific actions that will service a request.

• View management refers to finding and dispatching to the appropriate view.

Page 16: Design Patterns J2EE

13 March 2009

Front Controller Class diagram

Page 17: Design Patterns J2EE

13 March 2009

Front Controller Sequence diagram

Page 18: Design Patterns J2EE

13 March 2009

Context ObjectProblem:

You want to avoid using protocol specific system information outside of its relevant context.

Solution:

Use a Context Object to encapsulate state in a protocol-independent way to be shared throughout your application.

Encapsulating request data in a Context Object allows it to share with other parts of the application without coupling the application to a specific protocol. when a ContextObject encapsulates request state, it is also referred to as a RequestContext.

Page 19: Design Patterns J2EE

13 March 2009

For example, an HTTP request parameter exists for each field of an HTML form and a Context Object can store this data in a protocol-independent manner. Then other parts of the application simply access the information in the Context Object, without any knowledge of the HTTP protocol.

Strategies for Context Object implementation

• Request Context Map Strategy

• Request Context POJO Strategy

Page 20: Design Patterns J2EE

13 March 2009

Request Context POJO StrategyOne common example of the POJO strategy is the Struts framework ActionForm class.public class EmployeForm extends ActionForm {

private String gender = null;private String surname = null;

public String getSurname() {return surname;

} public void setSurname(String surname) {

this.surname = surname;}public String getGender() {

return gender;} public void setGender(String gender) {

this.gender = gender;……………………………………….

}}

Page 21: Design Patterns J2EE

13 March 2009

Transfer ObjectContext Object raises the question about its relationship to a Transfer Object ?

Transfer Objects carry state across remote tiers. While a Context Object acts as a Transfer Object when it is used for this purpose, a Context Object’s main goal is to share system information in a protocol-independent way, improving the reusability and maintainability of an application.

Purpose:

1.You want to transfer multiple data elements over a tier.

2.When an enterprise bean use a Transfer Object, the client makes a single remote method invocation to the enterprise bean instead of numerous remote method calls to get individual attribute values.

Page 22: Design Patterns J2EE

13 March 2009

Implementing the Transfer Object Pattern• Sample Code

Transfer Object is an arbitrary serializable Java Object referred to as a TO

Consider an example where a business object called Project is modeled and implemented as an entity bean. The Project entity bean needs to send data to its clients in a Transfer Object when the client invokes its getProjectData() method. The Transfer Object class for this example, ProjectTO.

// Transfer Object to hold the details for Project

public class ProjectTO implements java.io.Serializable { public String projectId; public String projectName; public String managerId; ………………………………// Transfer Object constructors... }

Page 23: Design Patterns J2EE

13 March 2009

Business Delegates

Purpose

You want to minimize coupling between clients and the business services, thus hiding the underlying implementation details of the services, such as lookup and access.You want to translate network application into application exceptions.

Solution

A Business Delegates act as a client-side business abstraction; it abstract and hide the implementation details of the business services. Using a Business Delegate reduces the coupling between the client and the system’s business services.

Page 24: Design Patterns J2EE

13 March 2009

Sequence Diagram

The Business Delegate typically uses a Service Locator to encapsulate the implementation details of business service lookup. When the Business Delegate needs to look up a business service, it delegates the lookup functionality to the Service Locator

Page 25: Design Patterns J2EE

13 March 2009

Service Locator

Purpose

1.You want to transparently locate business components and services in a uniform manner.

2. You want to centralize and reuse the implementation of lookup mechanisms for J2EE application clients.

3. You want to avoid performance overhead related to initial context creation and service lookups.

Page 26: Design Patterns J2EE

13 March 2009

Service Locator

Service Locator to implement and encapsulate service and component lookup. A Service Locator hides the implementation details of the lookup mechanism

• Problem:

Have JNDI code all over the place.Why should client care about the details of grabbing an ejb?Separation of concerns.Frequent object lookups and context creation can be resource-intensive.

• Solution Service Locator.

Page 27: Design Patterns J2EE

13 March 2009

Service Locator• Replaces this:

InitialContext ctx = new InitialContext();Object homeObject = ctx.lookup(“ejb/name”);EJBHome home = (EJBHome) PortableRemoteObject.narrow( homeObject, ejbObj.class);

• With this:EJBHome home = ServiceLocator.getInstance.getEjbHome(“ejb/name”);

• Similar for local beans, environment entries, data sources plus the added benefit of caching.

Page 28: Design Patterns J2EE

13 March 2009

Sample code of Service Locatorpackage ...;import ...;public class ServiceLocator {

private static ServiceLocator serviceLocator;private static Context context;protected ServiceLocator() throws Exception {

context = getInitialContext();}

public static synchronized ServiceLocator getInstance() throws Exception {if (serviceLocator == null) {

serviceLocator = new ServiceLocator();}return serviceLocator;

}

Page 29: Design Patterns J2EE

13 March 2009

Sample code of Service Locator

public static EJBHome getEjbHome(String ejbName,Throws Exception {

Object object = context.lookup(ejbName);EJBHome ejbHome = null;ejbHome = (EJBHome) PortableRemoteObject.narrow(object,ejbClass);if (ejbHome == null) { throw new Exception("Could not get home for " + ejbName);}

return ejbHome;}

}

Page 30: Design Patterns J2EE

13 March 2009

Service Locator class diagram

Page 31: Design Patterns J2EE

13 March 2009

Data Access ObjectForces

• Components such as bean-managed entity beans, session beans, servlets, and other objects like helpers for JSP pages need to retrieve and store information from persistent stores and other data sources like legacy systems, B2B, LDAP, and so forth.

• Persistent storage APIs vary depending on the product vendor. Other data sources may have APIs that are nonstandard and/or proprietary. These APIs and their capabilities also vary depending on the type of storage-RDBMS, object-oriented database management system (OODBMS), XML documents, flat files, and so forth. There is a lack of uniform APIs to address the requirements to access such disparate systems.

• Components need to be transparent to the actual persistent store or data source implementation to provide easy migration to different vendor products, different storage types, and different data source types.

SolutionUse a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data.

Page 32: Design Patterns J2EE

13 March 2009

Data Access Object Factory Strategies

Purpose

You can make Data Access Object creation highly flexible by adopting the Factory Method patterns.

When the underlying storage is subject to change from one implementation to another , this strategy provide an abstract DAO factory object that construct various type of concrete DAO factories, each factory support a different type of persistent storage implementation.

Page 33: Design Patterns J2EE

13 March 2009

Data Access strategy using factory method

• When the underlying storage is not subject to change from one implementation to another,

this strategy can be implemented using the Factory Method pattern to produce a number of DAOs needed by the application.

Page 34: Design Patterns J2EE

13 March 2009

DAO strategy using Abstract Factory • The DAO pattern can be made highly flexible by adopting the Abstract Factory.

• When the underlying storage is subject to change from one implementation to another, this strategy may be implemented using the Abstract Factory pattern.

• In this case, this strategy provides an abstract DAO factory object (Abstract Factory) that can construct various types of concrete DAO factories, each factory supporting a different type of persistent storage implementation.

• Once you obtain the concrete DAO factory for a specific implementation, you use it to produce DAOs supported and implemented in that implementation

.

Page 35: Design Patterns J2EE

13 March 2009

DAO strategy using Abstract Factory • When the underlying storage is subject to change from one implementation to another,

this strategy may be implemented using the Abstract Factory pattern.

Page 36: Design Patterns J2EE

13 March 2009

DAO strategy using Abstract Factory • This class diagram shows a base DAO factory, which is an abstract class that is inherited

and implemented by different concrete DAO factories to support storage implementation- specific access.

• The client can obtain a concrete DAO factory implementation such as RdbDAOFactory and use it to obtain concrete DAOs that work with that specific storage implementation. For example, the data client can obtain an RdbDAOFactory and use it to get specific DAOs such as RdbCustomerDAO, RdbAccountDAO, and so forth.

• The DAOs can extend and implement a generic base class (shown as DAO1 and DAO2) that specifically describe the DAO requirements for the business object it supports. Each concrete DAO is responsible for connecting to the data source and obtaining and manipulating data for the business object it supports.

Page 37: Design Patterns J2EE

13 March 2009

Session Façade• Problem:

Need very loose coupling between client and ever changing business tier.Data tier changing.Need flexibility to offer up business rules in different ways to multiple clients.Need to improve reuse.Too many method invocations between client and server, leading to network performance problems

• Solution: Session Façade.

Page 38: Design Patterns J2EE

13 March 2009

Session Façade

• Façade Pattern 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 provides a layer of abstraction to subsystem of session beans, entity beans and other components

• Implemented as a layer of stateless beans (sometimes statefull)• Provides a clean interface to execute business logic and workflow• Provides for automatic transaction support• Separates development roles• From OO point of view provides for layer of abstraction and encapsulation

Page 39: Design Patterns J2EE

13 March 2009

Session Façade PatternBefore:

Page 40: Design Patterns J2EE

13 March 2009

Session Façade PatternAfter:

Page 41: Design Patterns J2EE

13 March 2009

Session Façade Benefits• Benefits:• Lower network overhead• Separation of business logic from presentation • Inherent transaction support• Promotes reusability• Looser coupling

Page 42: Design Patterns J2EE

13 March 2009