Design Patterns

(source: Core J2EE Patterns written by Alur, Crupi, Malks)

1

Sang Shin sang.shin@sun.com
Technology Evangelist Sun Microsystems, Inc.
2

Agenda
● ● ●

Presentation tier design patterns Business tier design patterns Integration tier design patterns

3

Core J2EE Patterns

J2EE Pattern Catalog

4

Three Tiers
Presentation Tier Business Tier Integration Tier

5

Presentation-Tier Patterns ● ● ● ● ● Intercepting Filter Front Controller View Helper Composite View Service to Worker 6 .

Business-Tier Patterns ● ● ● ● Business Delegate Service Locator Session Facade Data Transfer Object (DTO) – (was Value Object) ● Data Transfer Object Assembler – (was Value Object Assembler) ● ● Composite Entity Value List Handler 7 .

Integration-Tier Patterns ● ● ● Connector Data Access Object Service Activator 8 .

Presentation-Tier Design Patterns 9 .

Presentation Tier Processing Client Pre/PostProcessor Control Logic Display Business Service Intercepting Filter 10 .

data transformation ● Adding and removing these “pre” and “post” processing components should be flexible – deployment time installation/configuration 11 . authentication. compression.Intercepting Filter: Forces ● Each service request and response requires common pre-processing and post-processing – logging. caching.

Intercepting Filter: Solution ● Create pluggable and chainable filters to process common services such that – – Filters intercept incoming and outgoing requests and responses Flexible to be added and removed without requiring changes to other part of the application Servlet filters for HTTP requests/responses Message handlers for SOAP requests/responses 12 ● Examples – – .

Intercepting Filter: Class Diagram Target_Resource Consumer FilterManager Service request intercepted by FilterManager Filter One FilterChain Filter Two 13 .

Intercepting Filter Pattern Sequence Diagram Consumer SecurityFilter Incoming Request Apply Forward request Apply Forward request Response Complete Request Processing Compression Filter LoggingFilter FrontController Forward response Outgoing response Apply Apply 14 .

// Complete the filter processing by either passing the control // to the next servlet filter in chain or to the target URI....3 Filter Public final class SecurityFilter implements Filter{ public void doFilter(ServletRequest req. } } <filter-mapping> <filter-name>SecurityFilter</filter-name> <servlet-name>ControllerServlet</servlet-name> </filter-mapping> 15 . chain.. ServletException{ // Perform security checks here . FilterChain chain) throws IOException.Intercepting Filter Pattern Sample Deployment Descriptor Sample code for writing Servlet 2. modified_res).doFilter(modified_req. ServletResponse res.

Presentation Tier Processing Client Pre/PostProcessor Control Logic Display Business Service Intercepting Filter Front Controller 16 .

Logging Can leverage filter pattern 17 . authorization.Front Controller: Forces ● There is a need for centralized controller for view selection and navigation (Model 2) – – – based on user entered data business logic processing client type ● Common system services are typically rendered to each request. so having a single point of entry is desirable – – Example: Authentication.

View Helper 18 . Command. Dispatcher.Front Controller: Solution ● Use a controller as an centralized point of contact for all requests – Promote code reuse for invoking common system services ● ● Can have multiple front controllers. each mapping to a set of distinct services Works with other patterns – Filter.

Front Controller: Consumer Sends Service request Implementation Strategy Controller <<JSP Front Strategy>> JSPController <<Servlet Front Strategy>> ServletController 19 .

Front Controller Sample Code Servlet-based Implementation Public class EmployeeController extends HttpServlet{ //Initializes the servlet public void init(ServletConfig config) throws ServletException{ super.init(config). HttpServletResponse response) throws ServletException. HttpServletResponse response) throws ServletException. java.io. response). } //Handles the HTTP POST Requests protected void doPost(HttpServletRequest request. IOException{ processRequest (request. } Sample Deployment Descriptor 20 . response).IOException{ processRequest (request. } //Destroys the servlet public void destroy(){} //Handles the HTTP GET Requests protected void doGet(HttpServletRequest request.

********************************************************************/ Command command= reqHelper. } Sample Deployment Descriptor 21 .getParameter("op")). // Dispatch control to the view dispatch(request.getCommand().Front Controller Sample Code Servlet Front Controller with Command Pattern //Processes requests for HTTP Posts and Gets protected void processRequest(HttpServletRequest request. IOException{ String resultPage. HttpServletResponse response) throws ServletException. // Command performs the actual operation resultPage = command. response).execute(request. resultPage).create(request. Behind the scenes. // Create a RequestHelper object that represent the client request specific information RequestHelper reqHelper = new RequestHelper(request). response. implementation of getCommand() method would be like * Command command = CommandFactory. /******************************************************************** * Create a Command object. Command object is an implementation of the Command * Pattern.

String page) throws ServletException. HttpServletResponse response.getRequestDispatcher(page).forward(request. IOException { RequestDispatcher dispatcher = getServletContext().Front Controller Sample Code Servlet Front Strategy with Dispatch Pattern //Implement the dispatch method protected void dispatch(HttpServletRequest request. } Sample Deployment Descriptor } 22 . dispatcher. response).

Business-Tier Design Patterns 23 .

Business Delegate Pattern: Forces ● ● ● Business service interface (Business service APIs) change as business requirements evolve Coupling between the presentation tier components and business service tier (business services) should be kept to minimum It is desirable to reduce network traffic between client and business services 24 .

Business Delegate Pattern: Solution ● Use a Business Delegate to – – – – – Reduce coupling between presentation-tier and business service components Hide the underlying implementation details of the business service components Cache references to business services components Cache data Translate low level exceptions to application level exceptions 25 .

.* BusinessService LookupService Lookup / create 26 .Business Delegate Pattern: Class Diagram BusinessDelegate 1 Uses 1.

1.1 Get service Lookup Service Business Service 1.2 Return business service 2. Invoke 2.1 Invoke 2.Business Delegate Pattern Sequence Diagram Client 1.1 Lookup 1.2 Invoke 27 . Create Business Delegate 1.1.

Business Delegate Pattern Implementation Strategies ● Delegate Adapter Strategy – Integrating two disparate systems require an Adapter ● ex) Adaptor changes XML request to native request Business Delegate proxies to the Session bean it is encapsulating May cache necessary data such as home or remote object handles to improve performance 28 ● Delegate Proxy Strategy – – .

resourcesession.getHome( "Resource".create().ResourceSessionHome. }catch(ServiceLocatorException ex){ //Translate ServiceLocator Exception into an Application Exception throw new ResourceException(. homeClass). Looks up Session facade home object // and then creates Session facade EJB object public ResourceDelegate() throws ResourceException{ try{ ResourceSessionHome resourceSessionHome = (ResourceSessionHome)ServiceLocator.. objResourceSession = resourceSessionHome. // Default constructor. } ... 29 .Business Delegate Pattern Sample Code using Delegate Proxy public class ResourceDelegate{ // Reference to Session facade EJB object private ResourceSession objResourceSession.class.. // Session facade's home object class private static final Class homeClass = myExamples.).getInstance().

). } // Method to reconnect using Session facade EJB object public void reconnect(String id) throws ResourceException{ try{ //Obtain an instance of ServiceLocator object ServiceLocator objServiceLocator = ServiceLocator.getInstance(). } } 30 . }catch(ServiceLocatorException ex){ //Translate the Remote Exception into an Application Exception throw new ResourceException(... // Obtain the service that corresponds to the given ID.Business Delegate Pattern Sample Code using Delegate Proxy // Another constructor that accepts a Handle ID and reconnects to the a priori // obtained session bean instead of creating new one public ResourceDelegate(String id) throws ResourceException{ super(). Each ID // corresponds to serialized EJBObject handle objResourceSession = (ResourceSession)ServiceLocator.getService(id). reconnect(id).

If any service exception arises..)..getResourceDetails(). } } //Remaining proxy methods to session facade ResourceSession . } 31 .).. public ResourceVO setCurrentResource(String resourceId) throws ResourceException{ try{ return objResourceSession.. }catch(RemoteException ex){ throw new ResourceException(. } } public ResourceVO getResourceDetails() throws ResourceException{ try{ return objResourceSession.. these methods // convert them into application specific exceptions such as ResourceException. etc. }catch(RemoteException ex){ throw new ResourceException(.Business Delegate Pattern Sample Code using Delegate Proxy // Business methods proxied to the Session Facade.setCurrentResource(resourceId). SkillSetException..

. .Service Locator Pattern: Forces ● Service lookup and creation involves complex interfaces and network operations – JNDI operation is complex ● ex) PortableRemoteObject.) ● Service lookup and creation operations are resource intensive and redundant – Getting JNDI context 32 ..narrow(..

Service Locator Pattern: Solution ● Use a Service Locator to – – – Abstract naming service usage Shield complexity of service lookup and creation Enable optimize service lookup and creation functions ● Usually called within Business Delegate object 33 .

Service Locator Pattern: Class Diagram Client Component 1 Uses 1..* Creates Uses InitialContext Uses Uses Lookup BusinessService Uses Lookup / create ServiceFactory <<Singleton>> ServiceLocator 34 .

1.1 Create 2.3 Return service 2.2 Return EJBHome 2.1.1 Create ServiceFactory BusinessService 2.2 Get Service 2.Service Locator Pattern: Sequence Diagram Client ServiceLocator InitialContext 1. Get Service 2. Lookup 2. Get Instance 1.1 Creates 35 .2.1.

Service Locator Pattern: ● Implementation Strategies Implementation strategies for Service Locator – – – – EJB Service Locator Strategy JMS Queue Service Locator Strategy JMS Topic Service Locator Strategy Combined EJB and JMS Service Locator Strategy 36 .

Service Locator Pattern public class ServiceLocator { private static ServiceLocator me.. } 37 .. }catch(NamingException ex){ throw new ServiceLocatorException(. InitialContext context = null. } } // Returns the instance of ServiceLocator class (singleton) public static ServiceLocator getInstance() throws ServiceLocatorException{ if (me == null){ me = new ServiceLocator(). } return me.). Sample code using EJB Service Locator private ServiceLocator() throws ServiceLocatorException{ try{ context = new InitialContext().

ObjectInputStream is = new ObjectInputStream(io)..getBytes()..... }catch(Exception ex){ throw new ServiceLocatorException(.ejb. } try{ byte[] bytes = new String(Id).ejb. InputStream io = new ByteArrayInputStream(bytes).Service Locator Pattern: Sample code using EJB Service Locator Strategy // Convert the given string into EJB Handle and then to EJB Object public EJBObject getService(String Id) throws ServiceLocatorException { if (Id == null){ throw new ServiceLocatorException(. return handle.). } } // Returns the string Id that represents the given EJBObject's handle // in serialized format public String getId(EJBObject session) throws ServiceLocatorException { .getEJBObject().Handle)is.).Handle handle = (javax..readObject(). javax. } 38 .

lookup(name). EJBHome home = (EJBHome)PortableRemoteObject.. return home. homeClass).)... } } // Other methods pertaining to getting service using a string ID or // getting a string ID based on the given service . Class homeClass) throws ServiceLocatorException{ try{ Object objRef = context. } 39 .. }catch(NamingException ex){ throw new ServiceLocatorException(.Service Locator Pattern Sample code using EJB Service Locator Strategy // Converts the serialized string into EJBHandle and then to EJBObject public EJBHome getHome(String name.narrow(objRef.

Service Locator Pattern Client code using EJB Service Locator public class SampleServiceLocatorClient{ public static void main(String[] args){ ServiceLocator objServiceLocator = ServiceLocator. try{ ResourceSessionHome objResourceSessionHome = (ResourceSessionHome)objServiceLocator.getInstance().getHome( myExamples.resourcesession..class). }catch(ServiceLocatorException ex){ // Client handles exception . } } } 40 ..ResourceSessionHome.

Ways to use Patterns ● 11. Building new architectures Analyzing existing architectures Refactoring existing architectures Evangelizing Technology using patterns ● ● ● 41 . 44. 33. 22.

Build Building New Architectures: eBay.com Request Handler Request Service Interface Business Service Client Navigation & Dispatch XML Response View Processor XSL 42 .

Com: Decomposition Request Handler Pre & Post Processor Command Processor Request Processor Navigation & Dispatch Navigator Response Request Dispatcher XML View Processor View Preparer View Creator XSL Service Interface Business Service Request Client 43 .Build 1 eBay.

Build 1 eBay.com: Applied Patterns Request Handler Intercepting Filter Request Navigation Navigator & Dispatch Dispatcher Service Locator Front Controller Service Interface Command Business Delegate Business Service Client Response View Processor Intercepting Filter View Processor Transformer Helper XML Core J2EE Pattern Strategy XSL 44 .

Anlyz Analyzing Existing Architectures: Struts Framework Request Action Servlet Action Mapping Action Client uses Response JSP View Action Forward Action Form 45 .

Anlyz Struts: Patterns Implemented Front Controller Action Servlet Action Mapping Command Action Request Client uses Response JSP View Action Forward Action Form Composite View View Helper 46 .

Refac Refactoring Existing Architectures: Ford Session Servlet Loader Request Manager Context Request Response 47 .

. 48 .Refac Ford: No clear responsibilities What is it managing? Servlet Loader Request Manager Context Session What does this do? Request Response Leave 'em alone! These are not what you think they are..

pluggable commands! Helper Bean Response Wrapper Business Delegate View 49 .Refac Ford: Refactored Solution Request Helper We know what this does now! Front Controller Clear responsibilities Session Command Factory Context Customized wrappers Request Wrapper Control Command View Command Extensible. reusable.

Thank You! 50 .

Sign up to vote on this title
UsefulNot useful