J2ee Design Patterns

  • October 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View J2ee Design Patterns as PDF for free.

More details

  • Words: 5,876
  • Pages: 109
J2EE Design Patterns Presented by: Dharini, E&R, Chennai

1

Acknowledgements • •

Core J2EE Patterns by Deepak Alur, John Crupi and Dan Malks http://java.sun.com/blueprints

2

2

Agenda • • • • •

Introduction to Patterns Goals of J2EE Patterns Presentation Tier Patterns Business Tier Patterns Integration Tier Patterns

3

3

Introduction • • •

Pattern describes a proven solution to a recurring design problem. – Solution to a problem in a given context A Pattern is a common, repeatable solution Patterns are generic and take many forms – Architectural – Design – Deployment

4

Defining Patterns A design pattern is defined as a common, repeatable solution to a recurring design problem. A design patterns abstracts and identifies the key aspects of a common design structure, and makes that common design structure useful for creating a reusable object-oriented design. The design pattern identifies the participating classes and instances and their roles, responsibilities and interactions Patterns are generic and take the following forms:  Architectural  Design  Deployment

4

Evolution of Patterns •

It all started in civil engineering and architecture.



Design patterns originated outside the computer industry.



Design patterns are discovered as much as created.

5

It all started in civil engineering and architecture. In the seventies, architecture was considered as a discipline that required a lot of experience. But over a period of time, people like Christopher Alexander surprised the community by publishing books on architecture, there by they made it possible for people who are even without specialized knowledge and experience to give architectural solutions. The idea was simple, he identified the similarities between architectures that proved to be good, and identified the principles and wrote them as solutions to common design problems. These were named as PATTERNS in architecture. The simplest patterns may be summed up in no more than a sentence or two. For ex: Using a database to store information for a website is a pattern. A complex one perhaps require more explanation. Note: UML is widely used to describe patterns In fact any developer who as build anything with J2EE, or even with significant components of J2EE has probably discovered at least one ore two of the patterns already. 5

Design Patterns ? “A pattern is a proven solution to a problem in a context “ “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem in such a way that you can use this solution a million times over, without doing it the same way twice.” - By Alexander “A pattern is a three-part rule, which expresses a relation between a certain context, a problem, and a solution” - By Gang of Four (GoF) (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides – GoF)

6

Design Patterns are recurring solutions to recurring problems. Patterns are gathered through experience and are based on proven solutions. A pattern becomes a pattern only after it has been verified several times in real world systems. Hence patterns gives us the following advantages. 1. It promotes reuse. 2. It prevent us from reinventing the wheel 3. It improves our productivity by making us work faster and efficiently. 4. Patterns also give us vocabulary, which improves communication between architects and designers. 5. Patterns encourage us to combine them to solve larger problems. Note: Finding patterns is a matter of experience and thought process and not novelty.

6

Identifying a pattern ASK when you have doubt ?



Identify patterns from experience



Look at your past projects



Analyse good performing applications



Identify pattern candidates



Verify the pattern thoroughly

7

We identify patterns from experience. Every experienced architect or designer has figured out that in all the majority of projects, similar problems occur and most interestingly, solutions to these problems are also similar. This does not mean that the actual solution will be exactly the same. However, it does mean that all solutions share basic concepts. When looked at from a point of abstraction, we could say that all these solutions and problems represent a common abstract problem with a common abstract solution. However, a set of solutions becomes a pattern only after they have been verified. Of-course verifying complex patterns in software engineering might be a little more difficult than verifying simpler architectural patterns. So don’t identify patterns directly, first identify pattern candidates. Pattern candidates should be standalone solutions with as few connections to the outer world as possible. We have to validate the pattern candidates. The thumb rule in validating the pattern is 1. The pattern should be proved in at least three different systems. Basically which means that the pattern should be verified thoroughly as possible. Pls Note: A pattern that cannot fulfill the goals can do more damage, and can bring bad reputation to patterns.

7

Using Design Patterns •

Understand it completely.



Check twice before using.



Study carefully the examples for the pattern



Choose names for the pattern participants that are meaningful for our application.



Define the interfaces, components, classes and relationship.



Apply the pattern

Be careful of Antipatterns 8

Before using a pattern, understand it completely. This requires that we study the solutions section, problem section, and the example section etc. Then we should understand all the components , classes, interfaces and objects that take part in the pattern and their relationships. We should check once again that whether we have selected the appropriate pattern. Note: Learning many patterns is not sufficient for becoming a good designer. We have to understand every pattern we learn and we should be clear on when to use which pattern.

8

Antipatterns



Mistakes are documented as Antipatterns



They are exact opposite of patterns

9

Antipatterns describe negative solutions, which cause more problems than they address. Antipatterns describes design solutions that do not work in practice due to unintended and unforeseen negative consequences. For example, a typical wrong decision made in the first J2EE applications was to model entity beans with a fine grained interfaces and accessing them directly. This added a considerable remote method invocation and transaction management overhead, which resulted in poorly performing and unscalable application.

9

Introducing J2EE Patterns • • • •

J2EE is a relatively new platform for delivering Web-based applications It is difficult to design reusable, flexible object oriented applications Task becomes more complex, when there are distributed and transactional objects. J2EE patterns facilitate the design process by providing a collection of proven design patterns

10

Introducing J2EE Patterns It is often challenging to design reusable, flexible object-oriented applications. When the objects are distributed and transactional, the task becomes even more complex. The design process can be facilitated with a collection of proven design patterns for developers to adopt J2EE components to understand different problems and solutions

10

Using J2EE Patterns • • • • • • •

Modularity Protection and Exposure Component Extensibility Roles and Responsibilities Contracts Pluggable behavior Performance

11

Using the J2EE Patterns When creating the design of the system, J2EE patterns can be chosen to ensure the following:  Modularity  Protection and Exposure  Component Extensibility  Roles and Responsibilities  Contracts  Pluggable behavior  Performance

11

Features of J2EE patterns •

The main goals of the J2EE patterns are – Reduce coupling and dependencies between components – Minimize network traffic



Built on other patterns, such as “Gang of Four” patterns

12

12

J2EE Patterns in terms of “Tiers” • • •

J2EE Platform is a multitiered system, the system is viewed in terms of “tiers” A tier is a logical partition of the separation of concerns in the system Five tiers are identified: – – – – –

• •

Client Tier Presentation Tier Business Tier Integration Tier Resource Tier

J2EE patterns are classified according to the tiered approach J2EE patterns addresses the following tiers – Presentation Tier – Business Tier – Integration Tier

13

13

J2EE Patterns - Introduction •

Three categories of patterns are identified – Presentation Tier Patterns – Business Tier Patterns – Integration Tier Patterns

14

14

Patterns and Partitioning • •

21 patterns partitioned into tiers along Blueprints lines Presentation Tier – –



Business Tier – –



Best practices for building presentation components JSP, Servlets, XML/XSL Concerned with managing persistence and business processing EJB, JNDI

Integration Tier – –

Issues surrounding Integration with other technology JDBC, JMS

15

15

Pattern Template • •

J2EE patterns are all structured according to a defined pattern template The following template is adopted for J2EE patterns – Problem – Forces – Solution • Structure • Strategies

– Consequences – Sample Code – Related Patterns

16

16

Pattern Template - Description •

Problem



Forces



Solution – Describe the solution approach briefly

– Design issues faced by the developer – Lists the reason and motivations that affect the problem and the solution – Structure • Uses UML diagrams to show the basic structure of the solution

– Strategies • Describe different ways a pattern can be implemented



Consequences – Describe the pattern trade-offs



Sample Code



Related Patterns

– Example implementations and Code listings – Other relevant patterns

17

17

Presentation Tier Patterns – Using Template

18

Front Controller Pattern

19

Front Controller Pattern •

Context – The presentation-tier request handling mechanism must control and co-ordinate processing of each user across multiple requests. – Such control mechanisms may be managed by a centralized manner

20

20

Front Controller Pattern - Problem • •

The system requires a centralized access point for presentation-tier request handling mechanism Centralized control mechanism will handle • • • •

Integration of system services Context Retrieval View Management View Navigation

21

21

Front Controller Pattern - Problem •

Problems that may occur without centralized mechanisms • Each view is required to provide its own system services, often resulting in duplicate code. • View navigation is left to views which results in mixed (blended) view content and navigation.



Distributed control is more difficult to maintain as the changes will often need to be made in numerous places.

22

22

Front Controller Pattern - Forces • • • • • •

Common system services processing such as authentication and authorization checks. Logic is handled in one central location Decision points exist for retrieval and manipulation of data. Multiple views are used to respond to similar business requests. Centralized point of contact for handling a request – to control and log a user’s progress through the site. System services and view management logic are relatively sophisticated.

23

23

Front Controller Pattern - Solution • •

A controller as the initial point of contact for handling a request. The controller manages – – – – –

Handling of request Delegate business processing Manage choice of an appropriate view Handling errors Manage the selection of content creation strategies.

24

24

Front Controller Pattern – Class Diagram

25

25

Front Controller Pattern - Participants •

Client



Controller

– – –



Object requesting the generation of the view. Initial point of contact for handling all requests in the system. Controller may delegate to a helper to complete authentication and authorization of a user to initiate contact retrieval.

Dispatcher –

Responsible for view management and navigation, managing the next view to present to the user

26

26

Front Controller Pattern – Participants •

View – –



Represents and displays information to the client. Retrieves information from a model

Helper • •

Responsible for helping a view or controller complete its processing. Also responsible for gathering data required by the view and store it in the intermediate model.

27

27

Front Controller Pattern – Sequence Diagram

28

28

Front Controller Pattern - Strategies •

Servlet Front Strategy – The Front Controller is implemented as a servlet. – This is the preferred to the JSP Front Strategy.



JSP Front Strategy



Base Front Strategy

– The Front Controller is implemented as a JSP Page – Implementing a controller base class whose implementation other controllers may extend.

29

29

Front Controller Pattern - Consequences • • •

Centralizes control Improves manageability of security Improves reusability

30

30

Front Controller Pattern – Related Patterns •

View Helper – Flow logic is factored into the controller and data handling code moves back into the helpers.



Intercepting Filter



Dispatcher View and Service To Worker

– Centralized control of request processing – Combines Front Controller and View Helper with a dispatcher

31

31

View Helper Pattern

32

View Helper Pattern •

Context – The system creates presentation content, which requires processing of dynamic business data.

33

33

View Helper Pattern - Problem • •

Changes occur often in the presentation tier and are difficult to manage when business logic and presentation logic are interwoven. This makes systems – Less flexible – Less reusable – Less resilient



Reduces modularity

34

34

View Helper Pattern - Forces •

Business data assimilation requirements are nontrivial. – Embedding business logic in the view causes maintenance problems. – It is desirable to promote a clean separation of labor by having different roles of Software developer and Web production team member – One view is used to respond to a particular business request.

35

35

View Helper Pattern - Solution • • •

A view contains only the formatting code Business processing responsibilities are delegated to helper classes implemented as JavaBeans or custom tags. Helpers store the view’s intermediate data model

36

36

View Helper Pattern – Class Diagram

37

37

View Helper Pattern - Participants •

Client



View

– – – –



Object requesting generation of the view. Represents and displays information to the client. Information that is used in a dynamic display is retrieved from a model. Helpers support views by encapsulating and adapting a model for use in display.

Helper – – – –

Responsible for helping a view or controller complete its processing. Responsible for gathering data required by view and storing this intermediate model. Also referred to as ValueBean sometimes. Typically implemented as JavaBeans and custom tags.

38

38

View Helper Pattern - Participants •

ValueBean – –



Another name for the helper Responsible for holding intermediate model state for use by a view.

Business Service – – –

Role that is fulfilled by the service the client is seeking to access. Service is accessed via a Business delegate. Role of Business delegate is to provide control and protection for the business service.

39

39

View Helper Pattern – Sequence Diagram

40

40

View Helper Pattern - Strategies •

JSP View Strategy – The view component is implemented as a JSP page – Preferred strategy



Servlet View Strategy



JavaBean Helper Strategy

– The view component is implemented as a Servlet – Helper is implemented as a JavaBean – JavaBeans are easily constructed and integrated into a JSP environment

41

41

View Helper Pattern - Strategies •

Custom Tag Helper Strategy



Business Delegate Helper Strategy

– The Helper is implemented as a custom tag (JSP 1.1 onwards only) – Helper components often make distributed invocations to the business tier. – Helper invokes a business service without knowing details about its physical implementation and distribution – May be implemented as a JavaBean

42

42

View Helper Pattern - Consequences • •

Improves Application Partitioning, Reuse and Maintainability Improves Role Separation

43

43

View Helper Pattern – Related Patterns •

Business Delegate – Delegate hides from the client the underlying details of looking up and accessing the business services – Also provide intermediate caching to reduce network traffic



Dispatcher view and Service to Worker



Front Controller

– Combines Front Controller and View Helper with a dispatcher

44

44

Service To Worker Pattern

45

Service to Worker Pattern •

Context – A Web based system that generates presentation content(view) based on a template and a dynamic model. – The system controls flow of execution and access to business data, from which it creates presentation content.

46

46

Service to Worker Pattern - Problem • •

Problem is the combination of the problems solved by the Front Controller and View Helper Patterns. The system does not have a centralized request handling mechanism for managing the application services for each request. – –

Business and formatting logic is embedded directly within the view. This makes the system less flexible, less reusable and less resilient to change. Mixing the business and system logic with the view reduces modularity and provides a poor separation of roles among team members.

47

47

Service to Worker Pattern - Forces • • • • •

Authentication and authorization checks are completed per request Scriptlet code within views should be minimized Business logic should be encapsulated in components other than the view Control flow is relatively complex and based on values from dynamic content Multiple views are commonly used for responding to the similar business requests.

48

48

Service to Worker Pattern – Solution • •

Combine the Front Controller and View Helper patterns to move some presentation logic forward into the controller and application logic back into Helpers. A Front Controller is the initial point of contact for the request and is responsible for managing many aspects of request handling – – –

System services such as authentication and authorization Delegation of business processing, choosing an appropriate view, selection of content-creation strategies. Preparing the model for use by the view , which it dispatches

49

49

Service to Worker Pattern – Class Diagram

50

50

Service to Worker Pattern - Participants •

Client



Controller



Dispatcher

– – – – –



Object requesting the generation of the view Initial point of contact for handling a request Responsible for view management and navigation Manages the choice of the next view to be presented to the user Can be encapsulated within the controller

View –

Represents and displays information to the client

51

51

Service to Worker Pattern - Participants •

Helper – –



ValueBean – –



Responsible for helping a view or controller complete its processing Also responsible for gathering data required by the view and storing this intermediate model. Another name for the helper Responsible for holding intermediate model state for use by a view

Business Service – –

Role that is fulfilled by the service the client is seeking to access. Accessed via a business delegate

52

52

Service to Worker Pattern – Sequence Diagram

53

53

Service to Worker Pattern - Strategies •

Servlet Front Strategy – The Front Controller is implemented as a servlet. – This is the preferred to the JSP Front Strategy.



JSP Front Strategy



JSP View Strategy

– The Front Controller is implemented as a JSP Page – The view component is implemented as a JSP page – Preferred strategy

54

54

Service to Worker Pattern - Strategies •

Servlet View Strategy



JavaBean Helper Strategy

– The view component is implemented as a Servlet – Helper is implemented as a JavaBean – JavaBeans are easily constructed and integrated into a JSP environment



Custom Tag Helper Strategy – The Helper is implemented as a custom tag (JSP 1.1 onwards only)

55

55

Service to Worker Pattern - Consequences • • • •

Centralized control Improves Modularity and Reuse Improves Application Partitioning Improves Role Separation

56

56

Service to Worker Pattern – Related Patterns •

Front Controller and View Helper – The Service to Worker pattern is the result of combining the View Helper pattern with a dispatcher, in coordination with the Front Controller pattern.



Dispatcher View – Another name for the combination of the Front Controller pattern with a dispatcher, and the View Helper pattern.

57

57

Intercepting Filter FilterOne FilterManager

Target FilterTwo

<> FilterChain (From Servlet)

FilterThree Filter (From servlet)

58

Provides a solution for preprocessing and post processing a request. It defines a flexible architecture, which allows us to declaratively apply filter for intercepting requests and responses. Servlet filters are an implementation of this pattern. The intercepting Filter design pattern allows intercepting a request and applying a set of filters to it and then rejecting the request or allowing it to pass through its intended target. Participants in the Intercepting Filter pattern are as follows 1. FilterManager – The filter manager manages the filter, sequencing them and initiating their processing in a filter chain. 2. FilterChain – The filter chain is a structure comprising a sequence of individual filters. 3. FilterOne,FilterTwo,FilterThree – The independent filters that can be associated with specific destination target. 4. Target- The target is the destination requested by the client.

58

Intercepting Filter <<Servlet>>

Session Filter

Authentication Filter

Validation Filterl

Front Controller Client 1: Request

1:1 Execute 1:1:1 Execute 1:1:1:1 Execute

59

The above diagram shows an implementation of the intercepting filter pattern, pls do look at the code section to see the implementation. In our example code, you could see a filter which does session authentication and another doing validation.

59

Declaring a Intercepting Filter The filter needs to be declared in the web.xml descriptor for the application This is the XML for declaring a session filter

SessionFilter hotel.SessionFilter SessionFilter /control/*

60

Only upon giving this entries in the web.xml the filter will be identified.

60

Business Tier Design patterns – Using Template

61

Business Tier • • • • • • •

Business Delegate Service Locator Session Façade Transfer Object Transfer Object Assembler Value List Handler Composite Entity

62

62

Business Delegate

63

Business Delegate •

Context – The system exposes the entire business service API to its clients, often across the network

64

64

Business Delegate •

Problem and Forces – Presentation-tier clients need access to business services directly exposing underlying implementation details – Business services APIs may change as business requirement changes so we need to minimize coupling between presentation-tier clients and the business service – Need to reduce network traffic between client and business services and provide caching mechanism to improve performance – Different clients, such as devices, Web clients, and thick clients, need access to business service

65

65

Business Delegate •



Solution – Use a Business Delegate to reduce coupling between presentation-tier clients and business services. – Provide abstraction and so hids the underlying implementation details of the business service, such as lookup and access details of the EJB architecture The Business Delegate will be responsible for: – Handling the Exceptions from business services – Transparently performing any retry and recovery operations necessary in the event of service failure without exposing it to client – Improving performance by caches results and reference to remote business services

66

66

Business Delegate •

Structure Class diagram representing Business Delegate Pattern

67

67

Business Delegate •

Participants and Responsibilities Sequence diagrams that illustrate typical interactions for the Business Delegate pattern

68

68

Business Delegate

69

69

Business Delegate •

Strategies – Delegate Proxy strategy • provides proxy function to pass the client methods to the session bean it is encapsulating. • cache any necessary data, including the remote references to the session bean's home or remote objects to improve performance by reducing the number of lookups. – Delegate Adapter strategy • E.g. in B2B environment, disparate systems may use an XML as the integration language. Integrating one system to another typically requires an Adapter [GoF] to meld the two disparate systems

70

70

Business Delegate •

Consequences – Reduces Coupling, Improves Manageability – Exposes Simpler, Uniform Interface to Business Tier – Performance improvement through caching – Translates Business Service Exceptions

71

71

Business Delegate •

Related Patterns – Service Locator The Service Locator pattern may be used to create the Business Delegate's Service Locator, hiding the implementation details of any business service lookup and access code. – Proxy [GoF] A Business Delegate may act as a proxy, providing a stand-in for objects in the business tier. – Adapter [GoF] A Business Delegate may use the Adapter pattern to provide coupling for disparate systems.

72

72

Service Locator

73

Service Locator •



Context – Service lookup and creation involves complex interfaces and network operations. Problem and Forces – EJB clients need to use the JNDI API to look up EJBHome objects – JMS clients need to use JNDI API to look up JMS components – context factory to use for the initial JNDI context creation is vendordependent – Initial context creation and service object lookups may impact application performance.

74

74

Service Locator •

Solution – Use a Service Locator object to abstract all JNDI usage and to hide the complexities of initial context creation, EJB home object lookup, and EJB object re-creation. – Multiple clients can reuse the Service Locator object to reduce code complexity, provide a single point of control – Service Locator can improve performance by providing a caching facility.

75

75

Service Locator •

Related Patterns – Business Delegate The Business Delegate pattern uses Service Locator to gain access to the business service objects like EJB objects, JMS topics, and JMS queues. – Session Facade The Session Facade pattern uses Service Locator to gain access to the enterprise beans that are involved in a workflow. – Transfer Object Assembler The Transfer Object Assembler pattern uses Service Locator to gain access to the various enterprise beans it needs to access to build its composite Transfer Object.

76

76

Session Façade

77

Session Façade •

Context – In multi-tiered application, business logic is encapsulated in server-side components. Business component expose interfaces and complexity to client

78

78

Session Façade •

Problem and Forces – Client calls interfaces provided by Business Objects directly and this leads to tight coupling, which leads to direct dependence between clients and business objects; – Too many method invocations between client and server, leading to network performance problems; – Provide a simpler interface to the clients by hiding all the complex interactions and interdependencies between business components – A unified service layer must be provided for coarse-grained access by all clients, based on use cases. – Business Object is not protected from misuse.

79

79

Session Façade •



Solution – Use a session bean as a facade to encapsulate the complexity of interactions between the business objects in a workflow. The Session Façade will be responsible for – Locating, creating and modifying the business objects – Providing a uniform coarse-grained service access layer to clients. – Hiding relationships between business objects.

80

80

Session Façade •

Structure Class diagram representing the Session Facade pattern

81

81

Session Façade •

Participants and Responsibilities Sequence diagram that shows the interactions of a Session Facade with two entity beans, one session bean, and a DAO, all acting as participants in fulfilling the request from the client

82

82

Session Façade

83

83

Session Façade •

Strategies – Stateless Session Facade Strategy • If the client interaction is non-conversational (State does not need to be maintained between method calls), implement Session Façade as Stateless session bean – Stateful Session Facade Strategy • If the client interaction is conversational (State does need to be maintained between method calls), implement Session Façade as Stateful session bean

84

84

Session Façade •

Consequences – Use-case approach to defining Session Façade interface – Simpler, uniform interface to the clients – Reduce coupling between clients and business objects – Less network traffic – Coarse-grained abstraction of workflow – Centralize security and transaction management

85

85

Session Façade •

Related Patterns – Facade [GoF] The Session Facade is based on the Facade Design pattern. – Service Locator The Session Facade is a coarse-grained object that allows encapsulation of the workflow by managing business data and business service objects interactions. The Session Facade can use the Service Locator pattern to reduce the code complexity and to exploit the benefits offered by the Service Locator. – Business Delegate The Session Facade is used by the Business Delegate when the client requests access to business services. The Business Delegate proxies or adapts the client request to a Session Facade that provides the requested service.

86

86

Transfer Object

87

Transfer Object •

Context – Application clients need to exchange data with enterprise beans.

88

88

Transfer Object •

Problem and Forces – Client invokes a business object's ( Session or Entity EJB ) get methods multiple times until it obtains all the attribute values – Every call to an enterprise bean is potentially a remote method call with network overhead. – The number of calls made by the client to the enterprise bean impacts network performance and so Application Performance.

89

89

Transfer Object •



Solution – When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client The Transfer Objects will be responsible for – Allowing client to make a single remote method invocation to the enterprise bean to request the Transfer Object instead of numerous remote method calls to get individual attribute values. – Allowing client to invoke accessor (or getter) methods on the Transfer Object to get the individual attribute values from the Transfer Object

90

90

Transfer Object •

Structure Class diagram that represents the Transfer Object pattern

91

91

Transfer Object •

Participants and Responsibilities The sequence diagram that shows the interactions for the Transfer Object pattern

92

92

Transfer Object

93

93

Transfer Object •

Strategies – Updatable Transfer Objects Strategy • Where the BusinessObject is implemented as a session bean. • In this strategy, the Transfer Object not only carries the values from the BusinessObject to the client, but also can carry the changes required by the client back to the business object.

94

94

Transfer Object – Entity Inherits Transfer Object Strategy • Where BusinessObject is implemented as an entity bean • The entity bean extends (or inherits from) the Transfer Object class. The only assumption is that the entity bean and the Transfer Object share the same attribute definitions.

95

95

Transfer Object •

Consequences – Simplifies Entity Bean and Remote Interface – Transfers More Data in Fewer Remote Calls – Reduces Network Traffic – May Introduce Stale Transfer Objects – Concurrent Access and Transactions

96

May Introduce Stale Transfer Objects Adopting the Updatable Transfer Objects Strategy allows the client to perform modifications on the local copy of the Transfer Object. Once the modifications are completed, the client can invoke the entity's setData() method and pass the modified Transfer Object to the entity. The entity receives the modifications and merges the new (modified) values with its attributes. However, there may be a problem with stale Transfer Objects. The entity updates its values, but it is unaware of other clients that may have previously requested the same Transfer Object. These clients may be holding in their local cache Transfer Object instances that no longer reflect the current copy of the entity's data. Because the entity is not aware of these clients, it is not possible to propagate the update to the stale Transfer Objects held by other clients Concurrent Access and Transactions When two or more clients concurrently access the BusinessObject, the container applies the transaction semantics of the EJB architecture. If, for an enterprise bean, the transaction isolation level is set to TRANSACTION_SERIALIZED in the deployment descriptor, the container provides the maximum protection to the transaction and ensures its integrity. For example, suppose the workflow for the first transaction involves obtaining a Transfer Object, then subsequently modifying the BusinessObject attributes in the process. The second transaction, since it is isolated to serialized transactions, will obtain the Transfer Object with the correct (most recently updated) values. However, for transactions with lesser restrictions than serialized, protection is less rigid, leading to inconsistencies in the Transfer Objects obtained by competing accesses. In addition, problems related to synchronization, stale Transfer Objects, and version control will have to be dealt with.

96

Transfer Object •

Related Patterns – Session Facade The Session Facade, frequently uses Transfer Objects as an exchange mechanism with participating entity beans. When the facade acts as a proxy to the underlying business service, the Transfer Object obtained from the entity beans can be passed to the client. – Transfer Object Assembler The Transfer Object Assembler is a pattern that builds composite Transfer Objects from different data sources. – Value List Handler The Value List Handler is another pattern that provides lists of Transfer Objects constructed dynamically by accessing the persistent store at request time.

97

97

Integration Tier Design patterns – Using Template

98

Data Access Object

99

Data Access Object •

Context – Access to persistent storage, such as to a database, varies depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.

100

100

Data Access Object •

Problem and Forces – Components such as bean-managed entity beans, session beans, servlets, and other objects uses appropriate APIs to achieve connectivity and manipulate the data source which introduces a tight coupling between the components and the data source implementation. – Persistent storage APIs vary depending on the product vendor. – Portability of the components is directly affected when specific access mechanisms and APIs are included in the components. – 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.

101

101

Data Access Object •



Solution – Use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. – DAO manages the connection with the data source to obtain and store data. The Data Access Object will be responsible for: – Hiding the data source implementation details from its clients – Exposing simple interfaces to business component

102

102

Data Access Object •

Structure Class diagram representing Data Access Object

103

103

Data Access Object •

Strategies – Automatic DAO Code Generation Strategy • Since each BusinessObject corresponds to a specific DAO, it is possible to establish relationships between the BusinessObject, DAO, and underlying implementations (such as the tables in an RDBMS). Once the relationships are established, it is possible to write a simple application-specific code-generation utility that generates the code for all DAOs required by the application. The metadata to generate the DAO can come from a developer-defined descriptor file

104

104

Data Access Object – Factory for Data Access Objects Strategy • The DAO pattern can be made highly flexible by adopting the Abstract Factory [GoF] and the Factory Method [GoF] patterns

105

105

Data Access Object •

Consequences – Access to persistence storage is transparent because the implementation details are hidden inside the DAO – Reduces Code Complexity in Business Objects – Enables Easier Migration – Adds Extra Layer

106

106

Data Access Object •

Related Patterns – Transfer Object A DAO uses Transfer Objects to transport data to and from its clients. – Factory Method [GoF] and Abstract Factory [GoF] The Factory for Data Access Objects Strategy uses the Factory Method pattern to implement the concrete factories and its products (DAOs). For added flexibility, the Abstract Factory pattern may be used.

107

107

References •

http://java.sun.com/blueprints

108

108

Thank You! [email protected]

109

Related Documents

Core J2ee Design Patterns
November 2019 20
J2ee Design Patterns
October 2019 28
J2ee Design Patterns
November 2019 14
Design Patterns
June 2020 16
Design Patterns
May 2020 17
Design Patterns
May 2020 17