100% found this document useful (1 vote)
85 views

JAVA Design Pattern

The document discusses design patterns in Java. It begins by defining design patterns as common solutions to recurring problems in object-oriented design. It then discusses that learning design patterns is important for communicating solutions effectively and becoming a better developer. The document goes on to describe some specific design patterns like MVC, Business Delegate, Composite Entity, Transfer Object, and Session Facade. It provides definitions and examples of when and how to use each pattern.

Uploaded by

bramesh95
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
85 views

JAVA Design Pattern

The document discusses design patterns in Java. It begins by defining design patterns as common solutions to recurring problems in object-oriented design. It then discusses that learning design patterns is important for communicating solutions effectively and becoming a better developer. The document goes on to describe some specific design patterns like MVC, Business Delegate, Composite Entity, Transfer Object, and Session Facade. It provides definitions and examples of when and how to use each pattern.

Uploaded by

bramesh95
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

1

JAVA DP

JAVA Design pattern

What is the design pattern?

If a problem occurs over and over again, a solution to that problem has been used
effectively. That solution is described as a pattern. The design patterns are
language-independent strategies for solving common object-oriented design
problems. When you make a design, you should know the names of some common
solutions. Learning design patterns is good for people to communicate each other
effectively. In fact, you may have been familiar with some design patterns, you
may not use well-known names to describe them. SUN suggests GOF (Gang Of
Four--four pioneer guys who wrote a book named "Design Patterns"- Elements of
Reusable Object-Oriented Software), so we use that book as our guide to describe
solutions. Please make you be familiar with these terms and learn how other people
solve the code problems.

Do I have to use the design pattern?

If you want to be a professional Java developer, you should know at least some
popular solutions to coding problems. Such solutions have been proved efficient
and effective by the experienced developers. These solutions are described as so-
called design patterns. Learning design patterns speeds up your experience
accumulation in OOA/OOD. Once you grasped them, you would be benefit from
them for all your life and jump up yourselves to be a master of designing and
developing. Furthermore, you will be able to use these terms to communicate with
your fellows or assessors more effectively.

Many programmers with many years experience don't know design patterns, but as
an Object-Oriented programmer, you have to know them well, especially for new
Java programmers. Actually, when you solved a coding problem, you have used a
design pattern. You may not use a popular name to describe it or may not choose
an effective way to better intellectually control over what you built. Learning how
the experienced developers to solve the coding problems and trying to use them in
your project are a best way to earn your experience and certification.

Remember that learning the design patterns will really change how you design
your code; not only will you be smarter but will you sound a lot smarter, too.

How many design patterns?


2
JAVA DP

Many. A site says at least 250 existing patterns are used in OO world, including
Spaghetti which refers to poor coding habits. The 23 design patterns by GOF are
well known, and more are to be discovered on the way.

Note that the design patterns are not idioms or algorithms or components.

What is the relationship among these patterns?

Generally, to build a system, you may need many patterns to fit together. Different
designer may use different patterns to solve the same problem. Usually:

 Some patterns naturally fit together


 One pattern may lead to another
 Some patterns are similar and alternative
 Patterns are discoverable and documentable
 Patterns are not methods or framework
 Patterns give you hint to solve a problem effectively

J2EE Patterns:--

1.MVC:

Definition:The Model/View/Controller(MVC) is an architecture design pattern.


Model means data, View means representation and Controller works on data and
representation. MVC focuses on decouple the triad relationships among data,
representation and controller.

Where to use & benefits

 Application architecture design.


 Any data related design, including non-visual application.
 Decouple complex object to improve maintainability.
 Increase object reusability.
 Achieve design flexibility
 Related patterns include
 Almost all patterns can be used with MVC.

History
3
JAVA DP

The Model/View/Controller(MVC) originates from Smalltalk, an OO


programming language.

Core issue

MVC consists of three kind of objects. The Model is an internal representation of


the data, the View is the screen presentation of GUI, and the Controller coordinates
changes between the Model and View.

SCJD project design

To achieve the MVC architecture in your project, you have to decouple View and
Model by Controller. Your GUI as View should be designed as a module. It can be
launched separately. Your data related classes as Model should be treated as a
module too. Your controller classes should response to any data change on the
GUI. Such design will increase reusability and flexibility.

Try to visualize that the user reacts with the GUI, a DataManager(Controller)
listens to the GUI's call. If the user needs to load data, such request is sent to the
DataManager, the DataManager starts loading, searching and extracting the
requested data from the server and sends it back to the GUI. GUI is responsible to
display data.

Here the server acts as Model, the DataManager acts as Controller and GUI acts as
View. The DataManager can be used for both remote and local modes (design two
constructors for both modes), the GUI can be replaced with any design and the data
related classes can be packaged together and put on local and server sides. All of
the three objects can be reused for other projects with little code alteration.

If you grasp such concept and skill, you will save a lot of time in designing and
developing your projects in the future. This is the so-called OOA/OOD.

2.Business Delegate:-

Definition

An intermediate class decouples between presentation-tier clients and business


services.

Where to use & benefits


4
JAVA DP

 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.

Example

Make a class deal with lookups and exception, acting as a representative of the
client components

3.Composite Entity:-

Definition

Use a coarse-grained interface to manage interactions between fine-grained or


coarse-grained and dependent objects internally. The Composite Entity is a coarse-
grained entity bean. It may be the coarse-grained object or hold a reference to the
coarse-grained object. Also known as Aggregate Entity.

Where to use & benefits

 Combine coarse-grained object and its related dependent objects into a


single entity bean.
 Multiple clients share persistent objects.
 Model a network of related business entities.
 In both local and distributed environment, use remote entity beans to model
dependent business objects or fine-grained objects.
 Improve performance by eliminating the parameter and return value
serialization and data transmission costs.
 Eliminate inter-entity relationships
 Improve manageability by reducing entity beans.
 Improve network performance
 Reduce database schema dependency
 Increase object granularity
 Facilitate composite transfer object creation.
 Overhead of multi-level dependent object graphs.
5
JAVA DP

 Related patterns include


 Transfer Object used to return to client and also used to serialize the
coarse-grained and dependent objects tree, or part of the tree, as required.
 Session Facade used to manage the inter-entity-bean relationships.

Transfer Object:

Definition:Using a serializable class to act as data carrier, grouping related


attributes, forming a composite value and working as a return type from remote
business method. Also known as Value object.

Where to use & benefits

 Get related values from remote business method.


 Fetch multiple values in one trip.
 Decrease network traffic.
 Minimize latency and server resource usage.
 Related patterns include
 Composite view

Example

In the J2EE server, the client tier may make several calls to retrieve data from the
enterprise bean. Even in the same machine, the every call from the client tier to the
server tier is a remote method call. Think about use Transfer Object design pattern
to retrieve related attributes and return a single object instead of each call just for
retrieving a single attribute value. The transfer object is passed by value to the
client. All calls to the transfer object instance are local calls to the client, so such
design saves a lot of network traffic.

Let's say that you have a remote banking system. If the user has five requests one
time, you should design your system to give response once, not five times. You
may need to group all return values from these five requests to an object carrier
and then return to client just once. Once the client program receives the instance of
this object, it invokes the accessors and gets value to display. The total network
traffic for one user just once.

Session Façade
6
JAVA DP

Definition:Provide a simple class or component that represents or contains


interactions between complex components

Where to use & benefits

 EJB session bean


 Provides a single & simple interface for complex system or components
 Simplify the process
 Clarify design
 Flexible and comprehensible
 Loosely coupling
 Related patterns include
 Facade make a complex system simpler by providing a unified or general
interface, which is a higher layer.

Example:Provide a step by step process for a complex system. For example, let a
component or user access a complex system by exposing a simple or a unified
interface to hide complexity to reach a loose coupling and flexible interaction.

4.Data Access Object:--

Definition

Adapt a uniform interface to access multiple databases like relational, unrelational,


object-oriented, etc.

Where to use & benefits

 Need to access multiple data sources like legacy systems, B2B, LDAP, and
so forth.
 Lack of uniform APIs to address the requirements to access disparate
systems.
 Persistent storage APIs vary depending on the product vendor.
 Adapt and encapsulate all access to the data source.
 Hide the data source implementation details from its clients.
 More portable and less code dependencies in components.
 Solve differences in the APIs which is used to access different persistent
storage mechanisms.
 Not useful for container-managed persistence.
7
JAVA DP

 Related patterns include


 factory method -- used to deal with different data sources.
 abstract factory -- used to make an abstract layer of access to data sources.
 transfer object -- used to transport data to and from its clients.

5.Front Controller

Definition:Using a single component to process application requests.

Where to use & benefits

 JSP or Servlet.
 Design request handling component.
 Channel all requests through a single controller.
 Centralize request processing and view selection.
 Reduce business logic in a view
 Improve manageability of security
 Promote code reuse across requests
 Avoid code duplication
 Related patterns include
 Command combined with multiple requests.
 Intercepting Filter both centralize control of certain types of request
processing.
 Page Controller -- an alternative way.

6.Intercepting Filter

Definition:A pluggable component design to intercept incomming requests and


outgoing responses, provide common services in a standard manner
(independently) without changing core processing code.

Where to use & benefits

 Logging and authentication.


 Enhance security.
 Add additional function to existing web application.
8
JAVA DP

 Decorate main process.


 Debug.
 Pre-processing or post-processing for specific clients.
 Uncompress incoming request.
 Convert input encoding schema.
 Being added or removed transparently or declaratively and triggered
automatically
 Improve reusability
 Deployment-time composability
 Each filter is loosely coupled
 Inefficient for information sharing.
 Related patterns include
 Front Control better suited to handling core processing.
 Template good for template filter strategy
 Decorator providing for dynamically pluggable wrappers.

Example:To create a basic filter, you need to:

1. implement Filter interface


2. implement doFilter method
3. call doFilter from FilterChain object
4. register the filter with the appropriate servlets and JSP pages
5. Mapping the filter to specific pages
6. disable the invoker servlet

General skeleton program

import javax.servlet.*;
import javax.servlet.http.*;
public class MyFilter implements Filter {
public void doFilter(ServletRequest request,
ServletResponse resonse,
FilterChain chain)
throws ServletException, IOException {
//work on request and response
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
//work on config
9
JAVA DP

}
public void destroy() {
//work on clean up
}
}

Register and filter mapping

//in web.xml file


<web-app>
...
Before the servlet description
<filter>
<filter-name>MyFilter</filter-name>
<display-name>MyCoolFilter</display-name>
<description>This is my cool filter</description>
<filter-class>somePackage.MyFilter</filter-class>
<init-param>
<param-name>yyy</param-name>
<param-value>/xxx/zzz</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/xxx.jsp</url-pattern>
</filter-mapping>

<!-- also apply to another servlet -->


<filter-mapping>
<filter-name>MyFilter</filter-name>
<servlet-name>xxx</servlet-name>
</filter-mapping>
...
</web-app>

You may use filter mapping and servlet mapping in web.xml file to diable the
invoker servlet to apply the filter.

7.Service Locator
10
JAVA DP

Definition:Centralizing distributed service object lookups, providing a centralized


point of control, acting as a cache that eliminates redundant lookups.

Where to use & benefits

 Lookup object in JNDI, RMI, JMS, etc.


 Encapsulate any vendor-specific features of lookup process
 Simplify the lookup process
 Improve the performance
 Related patterns include
 Singlton combined with service locator to make sure only one lookup object
exists.

Example:Use a container as cache to hold the lookup object. One application only
lookups same object once. Doing so will dramatically improve performance. Make
sure the container used is thread-safe.

8.Transfer Object

Definition:Using a serializable class to act as data carrier, grouping related


attributes, forming a composite value and working as a return type from remote
business method. Also known as Value object.

Where to use & benefits

 Get related values from remote business method.


 Fetch multiple values in one trip.
 Decrease network traffic.
 Minimize latency and server resource usage.
 Related patterns include
o Composite view

Example:In the J2EE server, the client tier may make several calls to retrieve data
from the enterprise bean. Even in the same machine, the every call from the client
tier to the server tier is a remote method call. Think about use Transfer Object
design pattern to retrieve related attributes and return a single object instead of
each call just for retrieving a single attribute value. The transfer object is passed by
value to the client. All calls to the transfer object instance are local calls to the
client, so such design saves a lot of network traffic.
11
JAVA DP

Let's say that you have a remote banking system. If the user has five requests one
time, you should design your system to give response once, not five times. You
may need to group all return values from these five requests to an object carrier
and then return to client just once. Once the client program receives the instance of
this object, it invokes the accessors and gets value to display. The total network
traffic for one user just once.

http://www.javacamp.org/designPattern/

You might also like