design patterns
TRANSCRIPT
![Page 1: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/1.jpg)
1
Design Patterns(source: Core J2EE Patterns
written by Alur, Crupi, Malks)
![Page 3: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/3.jpg)
3
Agenda● Presentation tier design patterns● Business tier design patterns● Integration tier design patterns
![Page 4: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/4.jpg)
4
J2EE Pattern Catalog
Core J2EE Patterns
![Page 5: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/5.jpg)
5
Three Tiers
PresentationTier
BusinessTier
IntegrationTier
![Page 6: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/6.jpg)
6
Presentation-Tier Patterns
● Intercepting Filter
● Front Controller
● View Helper
● Composite View
● Service to Worker
![Page 7: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/7.jpg)
7
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
![Page 8: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/8.jpg)
8
Integration-Tier Patterns
● Connector● Data Access Object● Service Activator
![Page 9: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/9.jpg)
9
Presentation-TierDesign Patterns
![Page 10: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/10.jpg)
10
Presentation Tier Processing
Client Business Service
ControlLogic Display
InterceptingFilter
Pre/Post-Processor
![Page 11: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/11.jpg)
11
Intercepting Filter: Forces
● Each service request and response requires common pre-processing and post-processing– logging, authentication, caching, compression,
data transformation
● Adding and removing these “pre” and “post” processing components should be flexible– deployment time installation/configuration
![Page 12: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/12.jpg)
12
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● Examples– Servlet filters for HTTP requests/responses– Message handlers for SOAP requests/responses
![Page 13: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/13.jpg)
13
Intercepting Filter: Class Diagram
Consumer
Service request intercepted by FilterManager
FilterManager
FilterChain
Target_Resource
Filter Two
Filter One
![Page 14: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/14.jpg)
14
Intercepting Filter PatternSequence Diagram
Consumer SecurityFilter CompressionFilter LoggingFilter FrontController
Incoming Request
Apply
Forward request
Complete Request Processing
Forward request
Apply
Response
ApplyForward response
ApplyOutgoing response
![Page 15: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/15.jpg)
15
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);}
}
<filter-mapping><filter-name>SecurityFilter</filter-name><servlet-name>ControllerServlet</servlet-name>
</filter-mapping>
![Page 16: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/16.jpg)
16
Presentation Tier Processing
Client Business Service
ControlLogic Display
InterceptingFilter
Front Controller
Pre/Post-Processor
![Page 17: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/17.jpg)
17
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, authorization, Logging– Can leverage filter pattern
![Page 18: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/18.jpg)
18
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, Command, Dispatcher, View Helper
![Page 19: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/19.jpg)
19
Front Controller:Implementation Strategy
ConsumerSends Service request
Controller
<<Servlet Front Strategy>>ServletController
<<JSP Front Strategy>>JSPController
![Page 20: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/20.jpg)
20
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);}
![Page 21: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/21.jpg)
21
Front Controller Sample CodeServlet Front Controller with Command Pattern
Sample 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 information RequestHelper 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 operation resultPage = command.execute(request, response);
// Dispatch control to the view dispatch(request, response, resultPage);}
![Page 22: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/22.jpg)
22
Front Controller Sample CodeServlet Front Strategy with Dispatch Pattern
Sample 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);}
}
![Page 23: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/23.jpg)
23
Business-TierDesign Patterns
![Page 24: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/24.jpg)
24
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
![Page 25: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/25.jpg)
25
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
![Page 26: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/26.jpg)
26
Business Delegate Pattern:Class Diagram
BusinessDelegateUses
BusinessService
LookupService
1 1..*
Lookup / create
![Page 27: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/27.jpg)
27
Business Delegate PatternSequence Diagram
Client BusinessDelegate
LookupService
BusinessService
1. Create1.1 Get service
1.1.1 Lookup1.1.2 Return business service
2. Invoke2.1 Invoke
2.2 Invoke
![Page 28: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/28.jpg)
28
Business Delegate PatternImplementation Strategies● Delegate Adapter Strategy– Integrating two disparate systems require an
Adapter● ex) Adaptor changes XML request to native
request
● Delegate Proxy Strategy– Business Delegate proxies to the Session bean it is
encapsulating– May cache necessary data such as home or remote
object handles to improve performance
![Page 29: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/29.jpg)
29
Business Delegate PatternSample Code using Delegate Proxy
public class ResourceDelegate{
// Reference to Session facade EJB objectprivate ResourceSession objResourceSession;
// Session facade's home object classprivate static final Class homeClass
= myExamples.resourcesession.ResourceSessionHome.class;
// Default constructor. Looks up Session facade home object // and then creates Session facade EJB object
public ResourceDelegate() throws ResourceException{try{
ResourceSessionHome resourceSessionHome = (ResourceSessionHome)ServiceLocator.getInstance().getHome(
"Resource", homeClass);objResourceSession = resourceSessionHome.create();
}catch(ServiceLocatorException ex){//Translate ServiceLocator Exception into an Application Exceptionthrow new ResourceException(...);
} ...
![Page 30: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/30.jpg)
30
Business Delegate PatternSample 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();reconnect(id);
}
// Method to reconnect using Session facade EJB objectpublic void reconnect(String id) throws ResourceException{
try{//Obtain an instance of ServiceLocator objectServiceLocator objServiceLocator = ServiceLocator.getInstance();
// Obtain the service that corresponds to the given ID. Each ID // corresponds to serialized EJBObject handle
objResourceSession = (ResourceSession)ServiceLocator.getService(id);
}catch(ServiceLocatorException ex){//Translate the Remote Exception into an Application Exceptionthrow new ResourceException(...);
}}
![Page 31: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/31.jpg)
31
Business Delegate PatternSample Code using Delegate Proxy
// Business methods proxied to the Session Facade. If any service exception arises, these methods// convert them into application specific exceptions such as ResourceException, SkillSetException, etc.public ResourceVO setCurrentResource(String resourceId) throws ResourceException{
try{return objResourceSession.setCurrentResource(resourceId);
}catch(RemoteException ex){throw new ResourceException(...);
}}
public ResourceVO getResourceDetails() throws ResourceException{try{
return objResourceSession.getResourceDetails();}catch(RemoteException ex){
throw new ResourceException(...);}
}
//Remaining proxy methods to session facade ResourceSession...
}
![Page 32: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/32.jpg)
32
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 operations are resource intensive and redundant– Getting JNDI context
![Page 33: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/33.jpg)
33
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
![Page 34: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/34.jpg)
34
Service Locator Pattern:Class Diagram
ClientComponent
UsesServiceLocator
BusinessService
1 1..*
Lookup / create
<<Singleton>>
Uses
UsesCreates
Uses
Uses
InitialContext
Lookup
ServiceFactory
![Page 35: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/35.jpg)
35
Service Locator Pattern:Sequence Diagram
Client ServiceLocator InitialContext ServiceFactory BusinessService
1. Get Instance 1.1 Create
2. Get Service2.1. Lookup
2.1.1 Create2.1.2 Return EJBHome
2.2 Get Service2.2.1 Creates
2.3 Return service
![Page 36: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/36.jpg)
36
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
![Page 37: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/37.jpg)
37
Service Locator PatternSample code using EJB Service Locatorpublic 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;
}
![Page 38: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/38.jpg)
38
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{...
}
![Page 39: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/39.jpg)
39
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
...}
![Page 40: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/40.jpg)
40
Service Locator PatternClient code using EJB Service Locator
public 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...
}}
}
![Page 41: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/41.jpg)
41
Ways to use Patterns● 1. Building new architectures
● 2. Analyzing existing architectures
● 3. Refactoring existing architectures
● 4. Evangelizing Technology using patterns
1
2
3
4
![Page 42: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/42.jpg)
42
Building New Architectures: eBay.com
Client
Request Handler
Navigation & Dispatch
Service Interface
View Processor
Request
ResponseXML
XSL
BusinessService
Build
![Page 43: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/43.jpg)
43
eBay.Com: Decomposition
Client
Request Handler
CommandProcessor
Pre & PostProcessor
RequestProcessor
Navigation & Dispatch
Navigator RequestDispatcher
Service Interface
View Processor
View Preparer View Creator
Request
ResponseXML
XSL
BusinessService
1Build
![Page 44: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/44.jpg)
44
eBay.com: Applied Patterns
Client
Request Handler
Navigation & Dispatch
Service Interface
View Processor
Request
Response XML
XSL
BusinessService
InterceptingFilter Command Business
Delegate
Service Locator
Front Controller
DispatcherNavigator
Transformer Helper
InterceptingFilter
Core J2EEPattern
Strategy
View Processor
1Build
![Page 45: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/45.jpg)
45
Analyzing Existing Architectures: Struts Framework
Client
Action Servlet
Action Mapping Action
ActionForward
ActionFormJSP View
Request
Response
uses
Anlyz
![Page 46: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/46.jpg)
46
Struts: Patterns Implemented
Client
Action Servlet
Action Mapping Action
ActionForward
ActionFormJSP View
Request
Response
uses
Front Controller Command
View HelperCompositeView
Anlyz
![Page 47: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/47.jpg)
47
Refactoring Existing Architectures: Ford
Servlet Loader Request ManagerSession
Context
Request Response
Refac
![Page 48: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/48.jpg)
48
Ford: No clear responsibilities
Servlet Loader Request ManagerSession
Context
Request Response
What does this do?
What is it managing?
These are not what you think they are...
Leave 'em alone!
Refac
![Page 49: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/49.jpg)
49
Ford: Refactored Solution
Front Controller Command FactorySession
Context
Control Command
View Command
Response Wrapper
Request Wrapper
Business Delegate
View HelperBean
Request HelperWe know what this does now!
Extensible, reusable, pluggable commands!
Clear responsibilities
Refac
Customized wrappers
![Page 50: Design Patterns](https://reader033.vdocuments.mx/reader033/viewer/2022051208/5474e20db4af9f451e8b4573/html5/thumbnails/50.jpg)
50
Thank You!