javaee design patterns
TRANSCRIPT
-
8/14/2019 JavaEE Design Patterns
1/36
1
Design PatternsDesign Patterns((source: Core J2EE Patternssource: Core J2EE Patternswritten by Alur, Crupi, Malks)written by Alur, Crupi, Malks)
-
8/14/2019 JavaEE Design Patterns
2/36
2
Agenda
Presentation tier design patterns Business tier design patterns
Integration tier design patterns
-
8/14/2019 JavaEE Design Patterns
3/36
3
J2EE Pattern Catalog
Core J2EE Patterns
-
8/14/2019 JavaEE Design Patterns
4/36
4
Three Tiers
PresentationTier
BusinessTier
IntegrationTier
-
8/14/2019 JavaEE Design Patterns
5/36
5
Presentation-Tier Patterns
Intercepting Filter
Front Controller
View Helper
Composite View
Service to Worker
-
8/14/2019 JavaEE Design Patterns
6/36
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
-
8/14/2019 JavaEE Design Patterns
7/367
Integration-Tier Patterns
Connector
Data Access Object
Service Activator
-
8/14/2019 JavaEE Design Patterns
8/368
Presentation-TierPresentation-TierDesign PatternsDesign Patterns
-
8/14/2019 JavaEE Design Patterns
9/369
Presentation Tier Processing
Client BusinessService
ControlLogic Display
InterceptingFilter
Pre/Post-Processor
-
8/14/2019 JavaEE Design Patterns
10/3610
Intercepting Filter: Forces
Each service request and responserequires common pre-processing and
post-processing logging, authentication, caching, compression,
data transformation
Adding and removing these pre andpost processing components should beflexible deployment time installation/configuration
-
8/14/2019 JavaEE Design Patterns
11/3611
Intercepting Filter: Solution
Create pluggable and chainable filters toprocess common services such that
Filters intercept incoming and outgoingrequests and responses
Flexible to be added and removed withoutrequiring changes to other part of the
application Examples
Servlet filters for HTTP requests/responses
Message handlers for SOAPrequests/responses
-
8/14/2019 JavaEE Design Patterns
12/3612
Intercepting Filter:
Class Diagram
Consumer
Service request interceptedby FilterManager
FilterManager
FilterChain
Target_Resource
Filter Two
Filter One
-
8/14/2019 JavaEE Design Patterns
13/36
13
Intercepting Filter PatternSequence Diagram
Consumer SecurityFilterCompression
FilterLoggingFilter FrontController
IncomingRequest
Apply
Forward request
Complete RequestProcessing
Forward request
Apply
Response
ApplyForward response
ApplyOutgoingresponse
-
8/14/2019 JavaEE Design Patterns
14/36
14
Intercepting Filter PatternSample code for writing Servlet 2.3 Filter
Sample Deployment DescriptorPublic final class SecurityFilter implements Filter{public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)
throws IOException, ServletException{// Perform security checks here.....
// Complete the filter processing by either passing the control// to the next servlet filter in chain or to the target URI.chain.doFilter(modified_req, modified_res);
}}
SecurityFilterControllerServlet
-
8/14/2019 JavaEE Design Patterns
15/36
15
Presentation Tier Processing
Client BusinessService
ControlLogic Display
InterceptingFilter
FrontController
Pre/Post-Processor
-
8/14/2019 JavaEE Design Patterns
16/36
16
Front Controller: Forces There is a need for centralized controller
for view selection and navigation (Model2) based on user entered data
business logic processing
client type
Common system services are typicallyrendered to each request, so having asingle point of entry is desirable Example: Authentication, authorization, Logging
Can leverage filter pattern
-
8/14/2019 JavaEE Design Patterns
17/36
17
Front Controller: Solution Use a controlleras an centralized point
of contact for all requests Promote code reuse for invoking common
system services
Can have multiple front controllers, eachmapping to a set of distinct services
Works with other patterns Filter, Command, Dispatcher, View Helper
-
8/14/2019 JavaEE Design Patterns
18/36
18
Front Controller:
Implementation Strategy
Consumer
Sends Service request
Controller
ServletController
JSPController
-
8/14/2019 JavaEE Design Patterns
19/36
19
Front Controller Sample CodeServlet-based Implementation
Sample Deployment DescriptorPublic class EmployeeController extends HttpServlet{
//Initializes the servletpublic void init(ServletConfig config) throws ServletException{
super.init(config);}
//Destroys the servletpublic void destroy(){}
//Handles the HTTP GET Requestsprotected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, java.io.IOException{
processRequest (request, response);}
//Handles the HTTP POST Requestsprotected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
processRequest (request, response);
}
-
8/14/2019 JavaEE Design Patterns
20/36
20
Front Controller Sample CodeServlet Front Controller with Command
PatternSample Deployment Descriptor
//Processes requests for HTTP Posts and Getsprotected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{String resultPage;
// Create a RequestHelper object that represent the client request specific informationRequestHelper reqHelper = new RequestHelper(request);
/********************************************************************* Create a Command object. Command object is an implementation of the Command* Pattern. Behind the scenes, implementation of getCommand() method would be like* Command command = CommandFactory.create(request.getParameter("op"));
********************************************************************/ Command command= reqHelper.getCommand();
// Command performs the actual operationresultPage = command.execute(request, response);
// Dispatch control to the view
dispatch(request, response, resultPage);}
-
8/14/2019 JavaEE Design Patterns
21/36
21
Front Controller Sample CodeServlet Front Strategy with Dispatch
PatternSample Deployment Descriptor//Implement the dispatch methodprotected void dispatch(HttpServletRequest request,
HttpServletResponse response, String page)throws ServletException, IOException {
RequestDispatcher dispatcher
= getServletContext().getRequestDispatcher(page);dispatcher.forward(request, response);
}}
-
8/14/2019 JavaEE Design Patterns
22/36
22
Business-TierBusiness-TierDesign PatternsDesign Patterns
-
8/14/2019 JavaEE Design Patterns
23/36
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 tominimum
It is desirable to reduce network traffic
between client and business services
-
8/14/2019 JavaEE Design Patterns
24/36
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 applicationlevel exceptions
-
8/14/2019 JavaEE Design Patterns
25/36
25
Business Delegate Pattern:
Class Diagram
BusinessDelegate
Uses
BusinessService
LookupService
1 1..*
Lookup / create
-
8/14/2019 JavaEE Design Patterns
26/36
26
Business Delegate Pattern
Sequence DiagramClient
BusinessDelegate
LookupService
BusinessService
1. Create1.1 Get service
1.1.1 Lookup
1.1.2 Return businessservice
2. Invoke
2.1 Invoke
2.2 Invoke
-
8/14/2019 JavaEE Design Patterns
27/36
27
Service Locator Pattern:
Forces Service lookup and creation involves
complex interfaces and network
operations JNDI operation is complex
ex) PortableRemoteObject.narrow(.., ..)
Service lookup and creation operationsare resource intensive and redundant Getting JNDI context
-
8/14/2019 JavaEE Design Patterns
28/36
28
Service Locator Pattern:
Solution Use a Service Locator to
Abstract naming service usage
Shield complexity of service lookup andcreation
Enable optimize service lookup and creationfunctions
Usually called within Business Delegateobject
-
8/14/2019 JavaEE Design Patterns
29/36
29
Service Locator Pattern:
Class DiagramClient
Component
Uses
ServiceLocator
BusinessService
1 1..*
Lookup / create
Uses
Uses
Creates
Uses
Uses
InitialContext
Lookup
ServiceFactory
-
8/14/2019 JavaEE Design Patterns
30/36
30
Service Locator Pattern:
Sequence DiagramClient ServiceLocator InitialContext ServiceFactory BusinessService
1. Get Instance 1.1 Create
2. Get Service
2.1. Lookup
2.1.1 Create
2.1.2 Return
EJBHome
2.2 Get Service
2.2.1 Creates2.3 Return
service
-
8/14/2019 JavaEE Design Patterns
31/36
31
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 LocatorStrategy
-
8/14/2019 JavaEE Design Patterns
32/36
32
Service Locator PatternSample code using EJB Service Locator
public class ServiceLocator{
private static ServiceLocator me;InitialContext context = null;
private ServiceLocator() throws ServiceLocatorException{try{context = new InitialContext();
}catch(NamingException ex){throw new ServiceLocatorException(...);
}}
// Returns the instance of ServiceLocator class (singleton)public static ServiceLocator getInstance() throws ServiceLocatorException{
if (me == null){me = new ServiceLocator();
}return me;
}
-
8/14/2019 JavaEE Design Patterns
33/36
33
Service Locator Pattern: Sample code
using EJB Service Locator Strategy// Convert the given string into EJB Handle and then to EJB Objectpublic EJBObject getService(String Id) throws ServiceLocatorException{
if (Id == null){throw new ServiceLocatorException(...);
}
try{byte[] bytes = new String(Id).getBytes();InputStream io = new ByteArrayInputStream(bytes);ObjectInputStream is = new ObjectInputStream(io);javax.ejb.Handle handle = (javax.ejb.Handle)is.readObject();return handle.getEJBObject();
}catch(Exception ex){
throw new ServiceLocatorException(...);}
}
// Returns the string Id that represents the given EJBObject's handle// in serialized format
public String getId(EJBObject session) throws ServiceLocatorException{
...}
-
8/14/2019 JavaEE Design Patterns
34/36
34
Service Locator PatternSample code using EJB Service Locator
Strategy// Converts the serialized string into EJBHandle and then to EJBObjectpublic EJBHome getHome(String name, Class homeClass)
throws ServiceLocatorException{try{
Object objRef = context.lookup(name);
EJBHome home= (EJBHome)PortableRemoteObject.narrow(objRef,homeClass);
return home;}catch(NamingException ex){
throw new ServiceLocatorException(...);}
}
// Other methods pertaining to getting service using a string ID or// getting a string ID based on the given service...
}
-
8/14/2019 JavaEE Design Patterns
35/36
35
Service Locator PatternClient code using EJB Service
Locatorpublic class SampleServiceLocatorClient{
public static void main(String[] args){ServiceLocator objServiceLocator = ServiceLocator.getInstance();try{
ResourceSessionHome objResourceSessionHome
= (ResourceSessionHome)objServiceLocator.getHome(myExamples.resourcesession.ResourceSessionHome.class);}catch(ServiceLocatorException ex){
// Client handles exception...
}}
}
-
8/14/2019 JavaEE Design Patterns
36/36
Thank You!