For More About Java Questions Check the below link

Java interview Questions
Please write your comments on this site to mailto:mailto:am4yours@gmail.com More links for Java click below link
|| Core Java 1 || || Java Design Patterns || || Ajax and Usage of Ajax || || Core Java 2 || || Servlet Interview Questions || || iBatis Developer Guide ||


Java Design Patterns

Java Design Patterns



1. Introduction
A design pattern is a general repeatable solution to a commonly occurring problem in a software design.
A design pattern is an abstraction of a solution at a very high level. Many designers and architects have defined the term design patterns in various ways.
Design patterns address the recurring design problems that arise in particular design situations and propose solutions to them. Design patterns are thus successful solutions to known problems. There are various ways to implement design patterns. There implementation details are called Strategies.
A design pattern prescribes a proven solution from experienced hands for a recurring design problem. Apart from describing the problem and prescribing the solution, the pattern will also explain the implementation issues involved and consequences, if any, of using the pattern. These solutions are generic in nature. They are described in the well-defined "Pattern Templates"; the most common one in use is the template defined by the "Gang of Four." The pattern templates usually have a name that offers a good idea as to what that pattern is all about, followed by where the pattern is applicable, the motivation, implementation issues, and other descriptions.
Use of such patterns makes the design of an application transparent. These patterns have been used successfully by developers in their respective work and hence the pros and cons of their use as well as implementation issues are known beforehand. All design patterns are reusable and can be adapted to a particular context; this gives developers flexibility. The use of design patterns related to J2EE applications offer the added advantage of providing solutions for J2EE platform technologies

2. Applications of Design Patterns
They have been proven. Patterns reflect the experience, knowledge and insights of developers who have successfully used these patterns in their own work.
They are reusable. Patterns provide a readymade solution that can be adapted to different problems as necessary.
They are expressive. Patterns provide a common vocabulary of solutions that can express very large solutions succinctly.
It is important to remember that patterns do not guarantee success. A pattern description indicates when the pattern may be applicable, but only experience can provide understanding of when a particular pattern will improve a design.

3. Origin of Design Patterns



The civil engineering patterns
In the 1960s and ’70s, Christopher Alexander, professor of architecture and director of the Center for Environmental Structure, along with his colleagues, wrote a number of books describing and documenting the principles of civil engineering from a layperson’s point of view. Of them, one of the most widely known books is A Pattern Language: Towns, Buildings, and Constructions. It provides practical guidance on how to build houses, construct buildings and parking lots, design a good neighborhood, and so forth. The book examines how these simple designs integrate with each other to create well-planned towns and cities. As its title suggests, the book describes 253 patterns that are split into three broad categories: towns, buildings, and construction.


4. Design Patterns classification

The Gang of Four Patterns
Software Designers extended the idea of design patterns to software development. Since features provided by the object-oriented languages, such as inheritance, abstraction, and encapsulation, allowed them to easily relate programming language entities to real-world entities, designers started applying those features to create common and reusable solutions to recurring problems that exhibited similar patterns.
Around 1994, the now famous Gang of Four(GoF)—Erich Gamma, Richard Helm,Ralph Johnson, and John Vlissides-documented 23 such software design patterns.
They classified the patterns at the very top level into three types of categories based on their purpose ---creational, structural, and behavioral.

Creational----Creational patterns deal with the ways to create instances of objects. The objective of these patterns is to abstract the instantiation process and hide the details of how objects are created or initialized.
Structural------Structural patterns describe how classes and objects can be combined to form larger structures and provide new functionality. These aggregated objects can be either simple objects or composite objects themselves.
Behavioral----Behavioral patterns help us define the communication and interaction between the objects of a system. The purpose of these patterns is to
reduce coupling between objects.

Though the GoF patterns served well in designing and developing object-oriented systems in both distributed and non distributed environments, they were not created with the distributed nature of large-scale enterprise systems in mind. As the demands for more distributed enterprise applications grew, the architects felt the need to document the solutions to recurring problems as they experienced the same problem occurring over and over again. They started extending and refining the patterns over a larger scale and with a broader scope.



The J2EE patterns
With the advent of the J2EE, a whole new catalog of deign patterns cropped up. Since J2EE is an architecture in itself that comprises other architectures, including servlets, Java Server Pages, Enterprise Java Beans, and so forth, it deserves its own set of patterns specifically tailored to the various types of enterprise applications that the architecture addresses.
There are 5 tiers in J2EE architecture. They are
a. Client
b. Presentation
c. Business
d. Integration
e. Resource
A Tier is a logical partition of the components involved in the system. Each tier is a loosely coupled with the adjacent tier. It is easier to understand the role of design patterns once we fully grasp the different tiers involved in a J2EE application.
Client---The tier comprises all the types of components that are clients of the enterprise application. Examples of client components are a Web browser, a hand held device, or another application that accesses the services of the enterprise application remotely.
Presentation---This tier interfaces with the client tier and encapsulates the presentation logic. It accepts the requests, handles authentication and authorization, manages client sessions, delegates the business processing to the business tier, and presents the client with the defined response. The components that make up this tier are filters, servlets, Java Beans, JSP pages, and other utility classes.
Business--- This tier is the heart of the enterprise application and implements the core business services. It is normally composed of the Enterprise Java Beans components that handle all the business processing rules.
Integration--- The job of this tier is to seamlessly integrate different types of external resources in the resource tier with the components of the business tier. The components that make up the integration tier use various mechanisms like JDBC,J2EE connector technology, or proprietary middleware to access the resource tier.
Resource--- This tier comprises the external resources that provide actual data to the application. The resources can either be data sources such as relational databases and file-based databases or such as applications running on mainframes. Other legacy systems, modern business-to-business(B2B)systems, and third party services like credit card authorization services.
Each of the 15 J2EE design patterns fall in one of the five tiers.

Presentation Tier
• Decorator Filter/Intercepting Filter
• Front Controller/Front Component
• View Helper
• Composite View
• Service to Worker
• Dispatcher View
Business Tier
• Business Delegate
• Transfer Object/Replicate Object
• Session Façade/Session Entity Façade/ Distributed Façade
• Aggregate Entity
• Transfer Object Assembler
• View List Handler/Page-by-Page Iterator /Paged List
• Service Locator
Integration Layer
• Data Access Object
• Service Activator
MVC is most commonly heard name in J2EE domain is in fact not a J2EE design pattern instead it is an architecture.

1)Decorator Filter/Intercepting Filter
Context—
• Client request may have many processing needs, and the system must be able to meet them.
• The System receives requests using multiple protocols, such as HTTP,FTP, or SMTP.
• The System must authorize or authenticate some requests, while handling others directly.
• The System needs to add or remove information from requests are responses before further processing.
Example--
If you have to build an enterprise system that doubles as a web portal and corporate intranet, you need to ensure that different client requests are handled appropriately. Not only must the system block requests for secure resources, it must also check for trusted IP addresses. Further, it must ensure that responses and requested resources are compressed/decompressed and encrypted/decrypted as needed.
Solution—
The Solution is to separate request/response processing from the rest of the system by creating filters. These objects, more fully provide a standardized, replaceable means of altering requests and responses as needed.
2)Front Controller/Front Component
Context—
• Managing an application for an individual user requires a number of considerations
• Controlling the application’s view and navigation
• Performing security processing to determine which resources and services are available for the user.
• Activating system services according to user selection
• Locating and accessing available resources according to user selection
Example—
In a Web application that accepts credit card information, several steps must be completed.
• Browse the catalog
• Add items to the shopping cart
• Confirm the checkout
• Get the name and shipping address of the receiver
• Get the name and billing address and the credit card information of the payer.
The different views associated with the store are decentralized. This means that they each control their navigation function, as well as perform the tasks needed to dispatch the user’s request.
Solution—
we need a single object to manage view control, resource/service accessing, error handling and initial request processing. This object acts as a front door to the client and is called as front controller or Front Component. Among the various strategies suggested by J2EE, the two simplest ones are using a servlet or JSP as front objects. All requests will be sent to the Front Controller and each request will have an action as a parameter.

3) Service Locator
Context-
Many systems depend on distributed processing and communication. In these cases, a number of concerns must be kept in mind:

• The system needs to locate and access resources and services across networks.
• If the services or resources are unavailable, the system must create local
implementations.
• New requests to a directory service require more time and resources than
cached repetitions of previous requests.

Example—
A large company contains a number of worldwide branches and needs to maintain
communication throughout. Many different applications require access to similar
external resources, such as personnel databases and inventory listings. In this case, the system uses Java Naming and Directory Interface (JNDI) to help components find one another. But as each object accesses JNDI separately, its responsiveness slows.

Solution –

The solution is to encapsulate the process of external communication into a Service Locator. With this method, the Locator object manages all of the complexity related to locating and interfacing resources across the network. Further, to reduce the amount of time associated with making requests, they can provide request caching. Finally, if external resources have vendor-specific interfaces, this object will manage the communication complexity and make accessing the resource transparent to the user.


4) Business Delegate

Context—

In an enterprise-scaled distributed application, typically the following situation arises:

• There are separate components to interact with the end users and to handle
business logic.
• These separate components reside in different subsystems, separated by a
network.
• The components that handle the business logic act as server components
because they provide business services to the clients by exposing the business
service API to the clients.
• The client components that use this API often reside in a remote system
separated by a network.
• There is more than one client using the API.
• There is more than one server component providing similar services, but with
minor differences in the API.

Example –
Let’s look at a real-world example. A company is building a web-based application
with JSP pages and servlets that need to access a set of business services. The management has decided not to develop the business services in-house, since they are readily available as off-the-shelf software from various vendors. In addition, the budget for the project is currently tight, so management has decided that they will purchase one of the more economical off-the-shelf solutions initially, and then when the money becomes available in a year, they will replace it with a more elaborate and expensive software solution.


Solution

Create a Business Delegate to handle all of the code that accesses the business services in the selected vendor software. When the vendor changes, the only changes that need to be made to the company’s application software are changes to the Business Delegate, to access the business services in the new vendor software. The JSP pages and servlets will not have to be modified.







The responsibilities of the components participating in this pattern are






• Client components—The client components, which are JSP pages and servlets in
the presentation tier, delegate the work of locating the business service providers
and the work of invoking the business service API methods to the Business Delegate objects.

• Business Delegate—The Business Delegate acts as a representative of the client
components. It knows how to look up and access the business services. It invokes the appropriate business services methods in the required order. If the API of the business service component changes, only the Business Delegate needs to be modified, without affecting the client components.

• Business service—A business service component implements the actual business
logic. Some examples of business service components are a stateless session EJB,
an entity EJB, a CORBA object, or an RPC server.

5) Transfer Object
Context
In distributed applications, the following situation typically arises:
• The client-side and the server-side components reside at remote locations and
communicate over the network.
• The server handles the database.
• The server provides getter methods to the clients so that the clients can call
those getter methods one by one to retrieve database values.
• The server provides setter methods to the clients so that the clients can call
those setter methods one by one to update database values.

Example
In the J2EE architecture, the business tier accesses the database directly or via the resource tier, and wraps the data access mechanism inside a set of entity beans and session beans. These entity and session beans expose the data via remote interfaces. The servlets and JSP pages in the presentation tier that need to access business data can do so by calling methods on the remote interfaces implemented by the beans.
As a specific example, suppose we maintain the address information in the database of the registered users of our enterprise application. In this case, the address information, which is a summation of four other pieces of data—street, city, state, and, zip—is a business entity. The access to this information is encapsulated by the application’s business tier with the help of a session bean called AddressSessionBean. AddressSessionBean exposes methods for the remote clients, such as getState (), setState(), getCity (), and setCity(). The servlets and the JSP pages then have to call each of the methods one by one on the remote server, as shown in figure below.

Solution

Create an object to encapsulate all of the attribute values that are required by the client application. This object is called the Transfer Object. When the client requests the data from the server, the server-side component gathers the data values and constructs the Transfer Object by setting its data values. This object is then sent to the client by value (not by reference), which means that the whole object is serialized and each of its bits is transferred over the network.
The client on the other side reconstructs this object locally with all the values intact. It can then query this local instance for all the attribute values. Because the Transfer Object is local on the client, all of the calls to this object are local and do not incur any network overhead. The Transfer Object on the client serves as a proxy for the properties of the remote object. This scenario is shown in figure below.
Now, instead of making multiple remote calls on the business object, Address-
Bean, to retrieve all the attributes, the client calls a single method, getAddress(),
which returns all the attributes structured in an AddressVO object.



6) Composite View

Context
In an enterprise-scaled distributed application, typically the following situation arises:
In distributed applications, the following situation typically arises:
• The web pages present data from various data sources, using multiple sub views that comprise a single display page.
• The server handles the database.
The Server may need to be restarted before clients see the modifications are updates to the template components.


Example
In real world application web pages present content from numerous data sources, using multiple sub views that comprise a single display page. The web pages are built by embedding formatting code directly with each atomic view. Atomic portion of the view content changes frequently , modification to the layout of multiple views is difficult and error prone when sub views are directly embedded and duplicated in multiple views. Embedding frequently changing portions of template text directly into views also potentially affects the availability and administration of the system.

Solution
The solution to this is to use composite views that are composed of multiple atomic sub views. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content.

This solution provides for the creation of a composite view based on the inclusion and substitution of modular dynamic and static template fragments. It promotes the reuse of atomic portions of the view by encouraging modular design. It is appropriate to use a composite view to generate pages containing display components that may be combined in a variety of ways. The layout of the page is managed and modified independent of the subview content.
The responsibilities of the components participating in these patterns are :

Composite View:--
A composite view is a view that is an aggregate of multiple subviews.

View Manager:--
The View Manager manages the inclusion of portions of template fragments into the composite view. The View Manager may be part of a standard JSP page runtime engine, in the form of the standard Java Server Pages (JSP page) pages include tag (), or it may be encapsulated in a JavaBeans helper (JSP page 1.0+) or custom tag helper (JSP page 1.1+) to provide more robust functionality. A benefit of using a mechanism other than the standard include tag is that conditional inclusion is easily done. For example,
certain template fragments may be included only if the user fulfills a particular role or certain system conditions are satisfied. Furthermore, using a helper component as a View Manager allows for more sophisticated control of the page structure as a whole, which is useful for creating reusable page layouts.

IncludedView--
An included view is a subview that is one atomic piece of a larger whole view. This included view could also potentially be a composite, itself including multiple subviews.

7) Data Access Object

Context
Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.
If the client needs to display or update a set of attributes that live on the server, these attributes could live in an entity bean or be accessible through a session bean. The client could get or update the data is by loading many parameters into a method call, when updating data on the server, or by making multiple fine-grained calls to the server to retrieve data. Every call between the client and server is a remote method call with substantial network overhead. If the client application calls the individual getter and setter methods that require or update single attribute values, it will require as many remote calls as there are attributes. The individual calls generate a lot of network traffic and affects severely the system performance.

To deal with suck kind of scenario we need to go for the DAO pattern.
Example
Suppose if the user want to send data a number of times through the program like entering user personal information or accessing just like online transactions services etc, we need to go for this approach.

Solution
The solution to this problem is to use a plain java classes called Value Objects or Transfer Objects which encapsulate the bulk business data. A single method call is used to send and retrieve the Transfer Object / Value Objects. 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.


8) Session Façade/Session Entity Façade/Distributed Facade
Context

Enterprise beans encapsulate business logic and business data and expose their interfaces, and thus the complexity of the distributed services, to the client tier.
In a multitiered Java 2 Platform, Enterprise Edition (J2EE) application environment, the following problems arise:
• 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;
• Lack of a uniform client access strategy, exposing business objects to misuse.

Example

An example demonstrating the use of Session Facade design pattern in a typical HR application.
Employees and Departments are used to store and retrieve employee and department information from the database. addition, the application allows the user to add a new department and assign existing employees to the newly added department. As this involves accessing two different entities, it should take place in one transaction. In this application only the admin user is allowed to add a new department.


Solution
Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.
The Session Facade abstracts the underlying business object interactions and provides a service layer that exposes only the required interfaces. Thus, it hides from the client's view the complex interactions between the participants. The Session Facade manages the interactions between the business data and business service objects that participate in the workflow, and it encapsulates the business logic associated with the requirements. Thus, the session bean (representing the Session Facade) manages the relationships between business objects. The session bean also manages the life cycle of these participants by creating, locating (looking up), modifying, and deleting them as required by the workflow. In a complex application, the Session Facade may delegate this lifestyle management to a separate object. For example, to manage the lifestyle of participant session and entity beans, the Session Facade may delegate that work to a Service Locator object

9) Service Activator

Context

An application has a service that it would like to make available to other applications.

Example

A Typical web application which requires the service of an authentication mechanism for a user is put in this service activator, and is invoked each time a user is login.

Solution
A Service Activator Service Activator can be one-way (request only) or two-way (Request-Reply). The service can be as simple as a method call—synchronous and non-remote—perhaps part of a Service Layer The activator can be hard-coded to always invoke the same service, or can use reflection to invoke the service indicated by the message. The activator handles all of the messaging details and invokes the service like any other client, such that the service doesn’t even know its being invoked through messaging.


The architecture of the Service Activator can be seen from the figure above.





10) Dispatcher View

Context
System controls flow of execution and access to presentation processing, which is responsible for generating dynamic content.
The Dispatcher View pattern, like the Service to Worker pattern, describes a common combination of other patterns from the catalog. Both of these macro patterns describe the combination of a controller and dispatcher with views and helpers. While describing this common structure, they emphasize related but different usage patterns.

Example
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 simple and is typically based on values encapsulated with the request.
View management logic is limited in complexity.

Solution
Combine a controller and dispatcher with views and helpers to handle client requests and prepare a dynamic presentation as the response. Controllers do not delegate content retrieval to helpers, because these activities are deferred to the time of view processing. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller, a view, or a separate component.
Dispatcher View describes the combination of the Front Controller and View Helper patterns with a dispatcher component. While this pattern and the Service to Worker pattern describe a similar structure, the two patterns suggest a different division of labor among the components. The controller and the dispatcher typically have limited responsibilities, as compared to the Service to Worker pattern, since the upfront processing and view management logic are basic. Furthermore, if centralized control of the underlying resources is considered unnecessary, then the controller is removed and the dispatcher may be moved into a view.
Since the Service to Worker and Dispatcher View patterns represent a common combination of other patterns from the catalog, each warrants its own name to promote efficient communication among developers. Unlike the Service to Worker pattern, the Dispatcher View pattern suggests deferring content retrieval to the time of view processing.
In the Dispatcher View pattern, the dispatcher typically plays a limited to moderate role in view management. In the Service to Worker pattern, the dispatcher typically plays a moderate to large role in view management.
A limited role for the dispatcher occurs when no outside resources are utilized in order to choose the view. The information encapsulated in the request is sufficient to determine the view to dispatch the request.





For example:
http://some.server.com/servlet/Controller?next=login.jsp
The sole responsibility of the dispatcher component in this case is to dispatch to the view login.jsp.
An example of the dispatcher playing a moderate role is the case where the client submits a request directly to a controller with a query parameter that describes an action to be completed:
http://some.server.com/servlet/Controller?action=login
The responsibility of the dispatcher component here is to translate the logical name login into the resource name of an appropriate view, such as login.jsp, and dispatch to that view. To accomplish this translation, the dispatcher may access resources such as an XML configuration file that specifies the appropriate view to display.
On the other hand, in the Service to Worker pattern, the dispatcher might be more sophisticated. The dispatcher may invoke a business service to determine the appropriate view to display.
The shared structure of these two patterns, as mentioned above, consists of a controller working with a dispatcher, views, and helpers.



The figure above shows the class diagram that represents the Dispatcher View pattern.


11) Service to Worker

Context
The system controls flow of execution and access to business data, from which it creates presentation content.
A service to Worker pattern like the Dispatcher View pattern, describes a common combination of other patterns from the catalog. Both of these macro patterns describe the combination of controller and dispatcher with views and helpers. While describing this common structure, they emphasize related but different usage patterns.




Example

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. View management logic is relatively sophisticated, with multiple views potentially mapping to the same request.


Solution
Combine a controller and dispatcher with views and helpers to handle client requests and prepare a dynamic presentation as the response. Controllers delegate content retrieval to helpers, which manage the population of the intermediate model for the view. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller or a separate component.

Service to Worker describes the combination of the Front Controller and View Helper patterns with a dispatcher component.
While this pattern and the Dispatcher View pattern describe a similar structure, the two patterns suggest a different division of labor among the components. In Service to Worker, the controller and the dispatcher have more responsibilities.
Since the Service to Worker and Dispatcher View patterns represent a common combination of other patterns from the catalog, each warrants its own name to promote efficient communication among developers. Unlike the Service to Worker pattern, the Dispatcher View pattern suggests deferring content retrieval to the time of view processing.
In the Dispatcher View pattern, the dispatcher typically plays a limited to moderate role in view management. In the Service to Worker pattern, the dispatcher typically plays a moderate to large role in view management.
A limited role for the dispatcher occurs when no outside resources are utilized in order to choose the view. The information encapsulated in the request is sufficient to determine the view to dispatch the request. For example,
http://some.server.com/servlet/Controller?next=login.jsp
The sole responsibility of the dispatcher component in this case is to dispatch to the view login.jsp.
An example of the dispatcher playing a moderate role is the case where the client submits a request directly to a controller with a query parameter that describes an action to be completed:
http://some.server.com/servlet/Controller?action=login
The responsibility of the dispatcher component here is to translate the logical name login into the resource name of an appropriate view, such as login.jsp, and dispatch to that view. To accomplish this translation, the dispatcher may access resources such as an XML configuration file that specifies the appropriate view to display.
On the other hand, in the Service to Worker pattern, the dispatcher might be more sophisticated. The dispatcher may invoke a business service to determine the appropriate view to display.
The shared structure of Service to Worker and Dispatcher View consists of a controller working with a dispatcher, views, and helpers.


The class diagram given above represents the Service to Worker pattern.


12)ViewHelper

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

Example
Business data assimilation requirements are nontrivial. Embedding business logic in the view promotes a copy-and-paste type of reuse. This causes maintenance problems and bugs because a piece of logic is reused in the same or different view by simply duplicating it in the new location. It is desirable to promote a clean separation of labor by having different individuals fulfill the roles of software developer and Web production team member.
One view is commonly used to respond to a particular business request.

Solution

A view contains formatting code, delegating its processing responsibilities to its helper classes, implemented as JavaBeans or custom tags. Helpers also store the view's intermediate data model and serve as business data adapters.
There are multiple strategies for implementing the view component. The JSP View Strategy suggests using a JSP as the view component. This is the preferred strategy, and it is the one most commonly used. The other principal strategy is the Servlet View Strategy, which utilizes a servlet as the view (see the section "Strategies" for more information).
Encapsulating business logic in a helper instead of a view makes our application more modular and facilitates component reuse. Multiple clients, such as controllers and views, may leverage the same helper to retrieve and adapt similar model state for presentation in multiple ways. The only way to reuse logic embedded in a view is by copying and pasting it elsewhere. Furthermore, copy-and-paste duplication makes a system harder to maintain, since the same bug potentially needs to be corrected in multiple places.
A signal that one may need to apply this pattern to existing code is when scriptlet code dominates the JSP view. The overriding goal when applying this pattern, then, is the partitioning of business logic outside of the view. While some logic is best encapsulated within helper objects, other logic is better placed in a centralized component that sits in front of the views and the helpers-this might include logic that is common across multiple requests, such as authentication checks or logging services.
If a separate controller is not employed in the architecture, or is not used to handle all requests, then the view component becomes the initial contact point for handling some requests. For certain requests, particularly those involving minimal processing, this scenario works fine. Typically, this situation occurs for pages that are based on static information, such as the first of a set of pages that will be served to a user to gather some information Additionally, this scenario occurs in some cases when a mechanism is employed to create composite pages .
The View Helper pattern focuses on recommending ways to partition your application responsibilities. For related discussions about issues dealing with directing client requests directly to a view.

Figure above is the class diagram representing the View Helper pattern.


13) View List Handler/Page-by-Page Iterator /Paged List

Context

This design pattern describes how to break a huge list of values into smaller pages and display the results one page at a time.


Example
In an application each user account is associated with many trade details and port folio details. Fetching all the data at once can be inefficient. It can take a long time, increase network traffic, and the user may only want to see a record or two.





Solution
Use a Page-by-Page Iterator to have a client object traverse a large list, one sublist or page of value objects at a time; each page can be as big or as small as the client desires.
Using this pattern makes the Less server-side data is transferred. More server side requests are made, The Iterator is not a robust Iterator.
The Iterator can be implemented as a Stateful Session Bean- so that it can keep the state of the Iterator for each client. It can cache the retrieved the pages which makes subsequent reads perform better.
We can use a Stateless Session Bean- as it has no state for the client; they have to specify what is wanted in each call. Cached pages are shared between clients.
Always use Value Objects for returned pages, do not return a collection of Entity Beans.
Use server side filtering to avoid unnecessary data transmitted to the client. Consider network load vs. server-side requests when determine the size of the pages.


14) Transfer Object Assembler
Context
In J2EE application, the server-side business components are implemented using session beans, entity beans, DAOs, and so forth. Application clients frequently need to access data that is composed from multiple objects.
Example
Separation of business logic is required between the client and the server-side components.
Because the model consists of distributed components, access to each component is associated with a network overhead. It is desirable to minimize the number of remote method calls over the network. The client typically needs only to obtain the model to present it to the user. If the client must interact with multiple components to construct the model on the fly, the chattiness between the client and the application increases. Such chattiness may reduce the network performance. Even if the client wants to perform an update, it usually updates only certain parts of the model and not the entire model. Clients do not need to be aware of the intricacies and dependencies in the model implementation. It is desirable to have loose coupling between the clients and the business components that implement the application model. Clients do not otherwise need to have the additional business logic required to construct the model from various business components.


Solution
Use a Transfer Object Assembler to build the required model or sub model. The Transfer Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model.
The Transfer Object Assembler constructs a composite Transfer Object that represents data from different business components. The Transfer Object caries the data for the model to the client in a single method call. Since the model data can be complex, it is recommended that this Transfer Object be immutable. That is, the client obtains such Transfer Objects with the sole purpose of using them for presentation and processing in a read-only manner. Clients are not allowed to make changes to the Transfer Objects.
When the client needs the model data, and if the model is represented by a single coarse-grained component (such as a Composite Entity), then the process of obtaining the model data is simple. The client simply requests the coarse-grained component for its composite Transfer Object. However, most real-world applications have a model composed of a combination of many coarse-grained and fine-grained components. In this case, the client must interact with numerous such business components to obtain all the data necessary to represent the model. The immediate drawbacks of this approach can be seen in that the clients become tightly coupled to the model implementation (model elements) and that the clients tend to make numerous remote method invocations to obtain the data from each individual component.
In some cases, a single coarse-grained component provides the model or parts of the model as a single Transfer Object (simple or composite). However, when multiple components represent the model, a single Transfer Object (simple or composite) may not represent the entire model. To represent the model, it is necessary to obtain Transfer Objects from various components and assemble them into a new composite Transfer Object. The server, not the client, should perform such "on-the-fly" construction of the model.

Figure given above shows the class diagram representing the relationships for the Transfer Object Assembler pattern.
15)Aggregate Entity
Context
Entity beans are not intended to represent every persistent object in the object model. Entity beans are better suited for coarse-grained persistent business objects.
Example
Entity beans are best implemented as coarse-grained objects due to the high overhead associated with each entity bean. Each entity bean is associated with an EJB home, remote object, bean implementation, and primary key, and each is managed by the container services.

Applications that directly map relational database schema to entity beans (where each row in a table is represented by an entity bean instance) tend to have a large number of fine-grained entity beans. It is desirable to keep the entity beans coarse-grained and reduce the number of entity beans in the application.
Solution
Use Aggregate Entity bean to model, represent, and manage a set of inter-related persistent objects rather than representing them as individual fine-grained entity beans. An Aggregate Entity bean represents a tree of objects.
To understand aggregation in the context of this pattern, one must first understand persistent objects and their relationships in an application. A persistent object is an object that is stored in some type of data store. Multiple clients usually share persistent objects.
Persistent objects can be classified into two types: coarse-grained objects and dependent objects.
A coarse-grained object is self-sufficient. It has its own life cycle and manages its relationships to other objects. Each coarse-grained object may reference or contain one or more other objects. The coarse-grained object usually manages the life cycles of these objects. Hence, these objects are called dependent objects. A dependent object can be a simple self-contained object or may in turn contain other dependent objects.
The life cycle of a dependent object is tightly coupled to the life cycle of the coarse-grained object. A client may only indirectly access a dependent object through the coarse-grained object. That is, dependent objects are not directly exposed to clients because their parent (coarse-grained) object manages them. Dependent objects cannot exist by themselves. Instead, they always need to have their coarse-grained (or parent) object to justify their existence.
Typically, you can view the relationship between a coarse-grained object and its dependent objects as a tree. The coarse-grained object is the root of the tree (the root node). Each dependent object can be a standalone dependent object (a leaf node) that is a child of the coarse-grained object. Or, the dependent object can have parent-child relationships with other dependent objects, in which case it is considered a branch node.
An Aggregate Entity bean can represent a coarse-grained object and all its related dependent objects. Aggregation combines inter-related persistent objects into a single entity bean, thus drastically reducing the number of entity beans required by the application. This leads to a highly coarse-grained entity bean that can better leverage the benefits of entity beans than fine-grained entity beans.
Without the Aggregate Entity approach, there is a tendency to view each coarse-grained and dependent object as a separate entity bean, leading to a large number of entity beans.
While there are many strategies in implementing the Aggregate Entity pattern, the first one we discuss is represented in the following class diagram. Here the Aggregate Entity contains the coarse-grained object, and the coarse-grained object contains dependent objects.
While there are many strategies in implementing the Aggregate Entity pattern, the first one we discuss is represented in the following class diagram. Here the Aggregate Entity contains the coarse-grained object, and the coarse-grained object contains dependent objects.


The Diagram above shows the Class diagram for the Aggregate Entity Design Pattern.

.






5. Anti Patterns
Anti patterns also called pitfalls, are classes of commonly reinvented bad solutions to problems. Anti-patterns are natural counterparts or follow-on to the study of design patterns. Programmers should try to avoid anti-patterns whenever possible, which requires diagnosing them as early as possible in the software life cycle.



6. Benefits and Drawbacks of Design Patterns


Benefits

• Design Patterns enable large-scale reuse of software architectures- They also help systems to enhance understanding

• Patterns explicitly capture expert knowledge and design tradeoffs, and make this expertise more widely available


• Patterns help improve developer communication- Pattern names form a vocabulary

• Patterns help ease the transition to object-oriented technology.


• Enable direct ruse of code

• Facilitate large amount of reuse than stand-alone functions or individual classes

Drawbacks

• Patterns do not lead to direct code reuse

• Patterns are deceptively simple


• Teams may suffer from pattern overload

• Patterns are validated by experience and discussion rather than by automated testing


• Integrating patterns into a software development process is a human-intensive activity

• High initial learning curve- Many classes and many levels of abstraction

• The flow of control for reactive dispatching is non-intuitive

• Verification and validation of generic components is hard







7. Best Practices to Design Patterns


• Do not recast everything as a pattern-Instead develop strategic domain patterns and reuse existing tactical patterns

• Institutionalize rewards for developing patterns


• Directly involve pattern authors with application developers and domain experts

• Clearly document when patterns apply and do not apply


• Manage expectations carefully


No comments:

Post a Comment