0% found this document useful (0 votes)
79 views

J2EE Design Patterns

Front Controller Removes Java code and business logic from JSPs Easier to maintain, by coders and designers alike Removes code duplication - Places logic in 'controller', and data in'model', presentation in the 'view' Command Strategy Divide and share command and strategy - handle individual requests moved out of the Front Controller servlet - Placed in separate lightweight components each component represents a specific command or action - Encapsulates the logic to perform the action.

Uploaded by

mks_mrityunjay
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

J2EE Design Patterns

Front Controller Removes Java code and business logic from JSPs Easier to maintain, by coders and designers alike Removes code duplication - Places logic in 'controller', and data in'model', presentation in the 'view' Command Strategy Divide and share command and strategy - handle individual requests moved out of the Front Controller servlet - Placed in separate lightweight components each component represents a specific command or action - Encapsulates the logic to perform the action.

Uploaded by

mks_mrityunjay
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 100

Why design?

Bad Design
Results in bad performance

Good Design vs Bad Design


Perform well even when overload

Good Design vs Bad Design


Scalability Reliability Availability

Good Design vs Bad Design

Decoupled Maintainable Extensible Flexible

Good Design vs Bad Design


Understandability Readability Clarity Well documented for changes

Good Design vs Bad Design


Traceability Testability

Good design vs Bad design


User Friendliness

J2ee architecture
N- Tiers Multi -layers

Multi layered architecture

10

Layering

11

Multi tiered architecture

12

TYPICAL J2EE Architecture

13

Logical Layering

14

Lets have some fun with pattern!!

15

Front Controller

16

Front Controller
Model-View-Controller (MVC) Removes Java code and business logic from JSPs Easier to maintain, by coders and designers alike Removes code duplication Places logic in controller, and data in model, presentation in the view Single point of entry into web application Centralise services Error handling, logging etc

17

Classes : Front Controller

18

Sequence : Front Controller

19

Front Controller
View sends request to Controller Controller processes request and manipulates the Model Controller dispatches View View displays Model

20

Multi tasking front controller


Can result in a bloated controller servlet Have a controller for each area of a system Use the Command and Controller strategy

21

Solution : Command Strategy

22

Divide and share

23

Command and strategy

24

Solution: Command Stratergy

25

Command Strategy
Logic to handle individual requests moved out of the Front Controller Servlet Placed in separate lightweight components Each component represents a specific command or action Encapsulates the logic to perform the action

26

Command Strategy
Handling of requests delegated to actions by the Front Controller Front Controller Servlet no longer bloated Controller is simply a action and view dispatcher Controller receives request from View Controller passes on request to Action Action modifies state of the Model Controller dispatches to View View renders Model Externalise mapping of requests to actions Pass a parameter with the request Controller maps this to a concrete action at request time
27

View Helper

28

Classes : View Helper

29

View Helper
Reduce the amount of presentation logic coded directly into the view Retrieval of data to display (e.g. from the model) Presentation logic (e.g. hiding information) General logic (e.g. iterating, etc)

30

Sequence : View Helper

31

View Helper
Adopt the View Helper pattern
Implement logic as JavaBeans or, preferably, as JSP standard actions or custom tags Provides separation between content and presentation of that content Can provide a more natural interface to the page author Eliminates a copy and paste style of reuse

32

View Helper
Typical JSP Code
<% String s; Iteratorit = myCollection.iterator(); while (it.hasNext()) { s = (String)it.next(); %> some body to be iterated over <% } %>

Custom tags Approach


<iterate id=s type=java.lang.String collection=<%= myCollection%>/> some body to be iterated over </iterate>

33

Dispatcher View

34

Dispatcher View
Dispatcher is responsible for view management and navigation . Can be encapsulated within a controller, a view or as a separate component. Dispatcher view suggests deferring content retrieval to the time of view processing.

Classes : Dispatcher View

36

Classes : Dispatcher View

37

Application Controller

38

Classes : Application Controller

39

Sequence : Application Controller

40

41

Service to worker

42

Service to worker
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 lessflexible, 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.
43

Classes : Service to worker

44

Sequence : Service to worker

45

Service to worker
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
46

Intercepting Filter

47

Intercepting Filter

48

Sequence : Intercepting Filter

49

Interceptor Pattern Uses


Authentication Access Validation System Logging System Debugging Data Encoding Browser Trapping Response Filtering
50

javax.servlet.Filter
void init(FilterConfig filterConfig) void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

void destroy()

51

javax.servlet.FilterChain
void doFilter(ServletRequest request,
ServletResponse response)

52

javax.servlet.http Wrappers
javax.servlet.http.HttpServletRequestWrapper javax.servlet.http.HttpServletResponseWrapper

These classes provide a complete set of methods implementing the HttpServletRequest and HttpServletResponse classes.

53

An Example of doFilter()
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)srequest; request.setCharacterEncoding(targetEncoding); // move on to the next chain.doFilter(srequest,sresponse); }

54

Deployment Descriptor
New tags filter and filter-mapping
<filter> <filter-name>EncodeFilter</filter-name> <display-name>EncodeFilter</display-name> <description></description> <filter-class>corepatterns.filters.encodefilter.EncodeFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

55

Composite View

56

Composite view

57

Sequence :Composite View

58

Composite View
When presentation tier components interact directly with the business services components like EJB, the presentation components are vulnerable to changes in the implementation of business services components

59

Business And Integration Layer

60

Business Delegate
Plain Java classes that hide EJB API complexity by encapsulating code required to discover, delegate to and recover from invocations on the session and message faade EJB layers. Use on large projects where the web team is separate from the EJB team .

Service Locator
Service lookup and creation involves complex interfaces and network operations. 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 vendor dependent Initial context

62

Service Locator

63

Service Locator

64

Service Locator
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.

65

Service Locator

66

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

67

Session Facade

68

Session Facade

69

Session Facade

70

Session Facade
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 coarsegrained access by all clients, based on use cases.

Business Object is not protected from misuse.


71

Session Facade
Use a session bean as a facade to encapsulate the complexity of interactions between the business objects in a workflow. The Session Faade will be responsible for Locating, creating and modifying the business objects Providing a uniform coarse-grained service access

72

Session Facade
Use-case approach to defining Session Faade 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

73

Fine Grained Entity Bean Design Idiom


Fine Grained Entity Bean Idiom
FGItem
<< EJBObject >>

FGItemBean
<< Entity Bean >>

ItemStateDAO
... Data Base

Client
...

getItemNumber() setItemNumber() getDescription() setDescription() getPrice() setPrice() getWeigth() setWeight() getWeightUOM() setWeightUOM() getManufacturerName() setManufacturerName()

getItemNumber() setItemNumber() getDescription() setDescription() getPrice() setPrice() getWeigth() setWeight() getWeightUOM() setWeightUOM() getManufacturerName() setManufacturerName()

FGItemHome
<< EJBHome >>

findByPrimaryKey() findListOfLength()

The client calls accessor methods on an entity bean to read the value of every individual data member

Coarse Grained Entity Bean Design Idiom


Coarse Grained Entity Bean Idiom
ItemState
getItemNumber() setItemNumber() getDescription() setDescription() getPrice() setPrice() getWeigth() setWeight() getWeightUOM() setWeightUOM() getManufacturerName() setManufacturerName()

Client
...

CGItemBean
<< Entity Bean >>

ItemStateDAO
... Data Base

getState()

CGItem
<< EJBObject >>

getState()

CGItemHome
<< EJBHome >>

findByPrimaryKey() findListOfLength()

The client uses an entity bean to retrieve a state object populated with database data

Service Adapter

76

DAO
The Data Access Object (DAO) J2EE pattern provides a technique for separating object persistence and data access logic from any particular persistence mechanism or API. The DAO approach provides flexibility to change an application's persistence mechanism over time without the need to re-engineer application logic that interacts with the DAO tier.

77

Data Access Patterns

The DataAccessObject (DAO) is the primary mechanism for retrieving and manipulating data from the data base. The ValueObject (VO) wraps data retrieved from a relational database in a Java object.
78

DataAccessObject

The Data Access Object consists of an Interface called DataAccessObject.java


The two functions of the DAO Pattern: Completely abstract away the data source in which the data the user is requesting resides.

Completely abstracts away all of the CRUD (Create, Replace, Update, Delete) logic normally associated with accessing a data source.
79

DataAccessObject
The DAO pattern abstracts away the tasks associated with retrieving and manipulating data by defining a Java interface that has 5 basic methods:
findByPrimaryKey( Object pPrimaryKey ) createValueObject() insert( ValueObject pValueObject ) update( ValueObject pValueObject ) delete( ValueObject pValueObject )

80

DataAccessObject
Remember, DataAccessObject.java is an interface, so to use it we define one or more member classes that implement the interface:

interface DataAccessObject +findByPrimaryKey(in primaryKey : String, ) : ValueObject +insert(in values : ValueObject) +update(in values : ValueObject) +delete(in values : ValueObject)

MemberDAO

81

Designing a Framework
DAOs: Not just about Relational Databases:

MemberDAO

MemberDAO

MemberDAO

MemberDAO

JDBC

JDO

Web Service SOAP envelope

XPath

Relational Database

Java Data Object

XML (Xindice)
82

ValueObject
The Value Object consists of an abstract class called ValueObject.java A Value Object Pattern wraps a row of data retrieved from a data source in a Plain Old Java (POJ) class: This lets the user deal with a logical view of the data instead of a physical view. Value objects hide the data types of the data being retrieved. Value objects hide the relationships that exist between tables in the database. Value objects are the glue that ties the tiers together. They are used to pass data back and forth between all tiers in the application.

83

ValueObject

84

ValueObject
The VO class has 3 status fields with their own get() and set() methods that are used to tell the DAO what to do with the VO: boolean insertFlag boolean updateFlag boolean deleteFlag At any given time, only 1 of the flags may be true. Setting any one of the flags resets the others to false. The VO class also provides a reset() method that clears all flags to false.
Finally, the VO class provides get() and set() methods for a rowVersion field. long rowVersion is used to implement the frameworks locking strategy.

85

ValueObject
Remember, ValueObject.java is abstract, so to use it we define one or more member classes that extend the VO:

86

J2EE applications generally have the search facility and have to search huge data and retrieve results. If an application returns huge queried data to the client, the client takes long time to retrieve that large data and If that application uses entity bean to search data, it has an impact on performance largely because EJB by nature has an overhead when compared to normal java object This process has an impact on performance for two reasons, 1. Application returns large amount of data to the client 2. Entity beans are used to retrieve huge data. The following figure illustrates this process.

87

Value List Handler

88

Value List Handler

89

Value List Handler


1. Use Data Access Objects (DAO) rather than Entity beans 2. Return small quantity of data multiple times iteratively rather than returning large amount of data at once to the client. Data Access Object encapsulates JDBC access logic. ValueListHandler caches list of Value objects thatare retrieved through DAO. When client wants to search data, It calls ValueListHandler that is in turn responsible for caching data and returning data to the client iteratively.

90

Session bean and entity bean methods execute synchronously that means the method caller has to wait till a value is returned. In some situations like sending hundred's of mails or firing a batch process or updating processes, the client does not have to bother about return value. If you use synchronous session and entity beans in such situations, they take a long time to process methods and clients have to wait till the method returns a value.

91

Service Activator
To avoid blocking of a client, use asynchronous message driven beans, so that client does not have to wait for a return value. If a client uses asynchronous messaging then the client need not wait for a return value but can continue its flow of execution after sending the message.

92

Service Activator

93

Service Activator
Client sends a message to JMS server, gets acknowledgement from the JMS server immediately in two step process and continues it's flow of execution. Whereas JMS server delivers the messages to Message driven bean (Service Activator) without blocking client's execution and Message driven bean executes messages. normal JMS consumers instead of Message driven beans. This process improves performance by reducing the client's blocking time considerably.

94

Business Delegate
An intermediate class decouples between presentation-tier clients and business services. Business delegate is responsible for: Invoking session beans in Session Facade. Acting as a service locator and cache home stubs to improve performance. Handling exceptions from the server side. (Unchecked exceptions get wrapped into the remote exception, checked exceptions can be thrown as an application exception or wrapped in the remote exception.unchecked exceptions do not have to be caught but can be caught and should not be used in the methodsignature.) Re-trying services for the client (For example when using optimistic locking business delegate will retry the method call when there is a concurrent access.).
95

Business Delegate

96

Business Delegate
Simplify the complicated relationship. Reduce coupling. Cache results and references to remote business services. Cut potentially costly round trips Hide the underlying implementation details of business service. Related patterns include Proxy combined to simplify the complexity.

97

Business Delegate

98

Key Points
1. Use ServiceLocator/EJBHomeFactory Pattern to reduce expensive JNDI lookup process. 2. Use SessionFacade Pattern to avoid direct client access to Entity beans thus reducing network calls. 3. Use MessageFacade/ServiceActivator Pattern to avoid large method execution process. 4. Use ValueObject Pattern to avoid fine grained method calls over network. 5. Use ValueObjectFactory/ValueObjectAssembler Pattern to avoid multiple network calls for a single client request. 6. Use ValueListHandler Pattern to avoid using Entity beans and send data iteratively to the client. 7. Use CompositeEntity Pattern to avoid inter Entity bean overhead.
99

Design Unique

!!!But Suit the Pattern


100

You might also like