Java Design Pattern -

eyelashesnectarineΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 4 χρόνια και 8 μήνες)

84 εμφανίσεις


Shishir Kumar







Convert the interface of a class into another
interface clients expect. Adapter lets classes
work together that couldn't otherwise because
of incompatible interfaces.

AC Power Adapters

• Electronic products made for the USA cannot be
used directly with electrical outlets found in most
other parts of the world

• US 3
prong (grounded) plugs are not compatible
with European wall outlets

• To use, you need either

• An AC power adapter, if the US product has a
“universal” power supply, or

• An AC power convertor/adapter, if it doesn’t

Object Adapters

Object Adapters use a compositional technique to adapt one
interface to another. The adapter inherits the target interface that
the client expects to see, while it holds an instance of
Object adapters enable the client and the

to be completely
decoupled from each other. Only the adapter knows about both of

Class Adapters

Class adapters use multiple inheritance to achieve their goals. As in the

adapter, the class adapter inherits the interface of the client's target.

However, it also inherits the interface of the

as well. Since Java

does not support true multiple inheritance, this means that one of the

interfaces must be inherited from a Java Interface type. Note that either or

both of the target or

interfaces could be an Java Interfaces. The

request to the target is simply rerouted to the specific request that was

inherited fro the


Difference between Object Adapters and Class Adapters

As Object Adapter uses composition it can not only adapt an

class, but any
of its subclasses. It is flexible.

Class Adapter is committed to only one
. But again it has an advantage as no
need to implement the entire
. It can just override the


and also can override the behavior as it is sub classing.

Note that class adapters have a problem with name conflicts if methods of the same
signature exist on both the target and the
. Note that just because two objects
have methods that have the same signature (syntax), it does not guarantee that the
two methods have the same meaning or behavior (
). That is, the two
methods do not necessarily map directly to each other. Object adapters do not have
this problem.

Class adapters are simpler than object adapters in that they involve fewer classes and
are useful if total decoupling of the client and

is not needed.

Client only understands the

for inserting pegs using the insert() method. At
back end application should reuse insert logic
within round pegs?

One Way Adaptor (Object Adaptor)

Two Way Adaptor (Class Adaptor)

Case Study II:

Build web application where user input data from
UI. Data can be saved within application database
and/or routed to mainframe. Mainframe is
proprietary system and we do not have control
over same.

The client makes a request on the adapter by invoking a method
from the target interface on it

The adapter translates that request into one or more calls on the

using the


The client receives the results of the call and never knows there is
an adapter doing the translation

We can not change the library interface, since we may
not have its source code. Even if we did have the
source code, we probably should not change the library
for each domain
specific application

Sometimes a toolkit or class library can not be used
because its interface is incompatible with the interface
required by an application

You want to create a reusable class that cooperates
with unrelated classes with incompatible interfaces

Implementation Issues

How much adapting should be done?

Simple interface conversion that just changes operation names and
order of arguments

Totally different set of operations

Before Java’s new collection classes, iteration over
a collection occurred via

() :

() : Object

With the collection classes, iteration was moved to
a new interface:


next(): Object

remove(): void

There’s a lot of code out there that makes use of
the Enumeration interface hence

Adaptor pattern

Decouple an abstraction or interface from its
implementation so that the two can vary

Simulate Persistence API

From application layer developer want to fetch information
from persistence system. Persistence system can be RDBMS
Database (can be any data base E.g. Oracle, Sybase or File

In this scenario there are two interface

a) Application layer

End client interact

b) Persistence layer

Interface define persist/fetch

Want to separate abstraction and
implementation permanently

Hide implementation details from clients

Want to improve extensibility

Real World Example:

DAO , Persistence Layer

Image (jpeg/png) display on different Operation

The image structure is the same across all operating systems, but the how it's viewed (the
implementation) is different on each OS.

The Template Method defines the steps of an
algorithm and allows sub class to provide the
implementation for one or more steps.

Template Method let subclass redefine certain
steps of an algorithm without changing the
algorithm’s structure.


behavior that can be overridden within
subclass to control algorithm behavior.

Application for processing flat file for

a) Stock and b) Derivatives.


Stock support CSV format where as Derivative
support txt

Stock data is separated by delimiter “,” where as
Derivative data within Flat file separated by “|”.
Data is persisted within database.

System can configure logging into system
optionally for data under process.

Want to have control over algorithm to avoid duplicate

Use Template if you are aware of requirement
complexity/algorithm. This is for code reuse and allow
subclass to specify behavior.

Real World Example:

(explained next slide)


Arrays sort, mergeSort
(Refer Head First Book)


(Refer Head First Book)

HibernateCallback used in HibernateTemplate's
execute(..) methods
(Refer Spring Blogs)



Servlet Life Cycle




Service method is an abstract method in GenericServlet Class.

HttpServlet extends GenericServlet and implement service method.

Based on HTTP request type, HTTPServlet invokes


doGet, doPost, doHead, doPut, doDelete, doTrace, doOptions

Developers extend HttpServlet and write meaningful method

doGet, doPost


HttpServlet service method define template for handling HTTP requests.

Hollywood Principle

"Don't call me, I will call you“

Template method enforces "Open Closed principle". A
class should be open for extension, but closed for

Strategy pattern defines a family of algorithms,
encapsulates each one and makes them

Strategy lets the algorithm vary independently
from clients that use it.

Subclasses decide how to implement steps in
an algorithm.

Application for processing flat file for

a) Stock and b) Derivatives.


Validate File format/type against system configuration

Stock/Derivative data can be stored in database or
content repository (as XML)

File can be routed to third party system Bloomberg (via
SOAP) or other customer (JMS).

Investment Bank can do below action

Indus Bank: validate, store data (database) and route to

USB Bank: validate, store (Repo) and route to Bloomberg

ABC Bank: validate, store (DB) and route to other customer



common method to validate File
format/type (independent of investment type


Parse and Store

parse data based on investment
type (Stock/Derivative) and store within database or
content repository system in XML format


file to third party system (via SOAP) or
Content repository system

Many related classes differ only in their behavior

You need different variants of an algorithm

An algorithm uses data that clients shouldn't know
about. Use the Strategy pattern to avoid exposing
complex, algorithm
specific data structures.

A class defines many behaviors, and these appear
as multiple conditional statements in its
operations. Instead of many conditionals, move
related conditional branches into their own
Strategy class

Real World Example:

Swing GUI Text components

Java AWT


Provides an alternative to subclassing the Context
class to get a variety of algorithms or behaviors

Eliminates large conditional statements

Provides a choice of implementations for the same


Increases the number of objects

All algorithms must use the same Strategy interface