by shishir kumar contact: [email protected]

29
JAVA DESIGN PATTERN By Shishir Kumar Contact: [email protected]

Upload: fay-porter

Post on 04-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: By Shishir Kumar Contact: Shishirroy2000@gmail.com

JAVA DESIGN PATTERN

By

Shishir KumarContact: [email protected]

Page 2: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Agenda

Decorator Adaptor Bridge Template Strategy

Page 3: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Adapter Pattern

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

Page 4: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Adapter Cont.

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

Page 5: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Type Of Adapter

Object AdaptersObject 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 adaptee. Object adapters enable the client and the adaptee to be completely decoupled from each other. Only the adapter knows about both of them.

Class AdaptersClass adapters use multiple inheritance to achieve their goals. As in the object adapter, the class adapter inherits the interface of the client's target. However, it also inherits the interface of the adaptee 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 adaptee interfaces could be an Java Interfaces. The request to the target is simply rerouted to the specific request that was inherited fro the adaptee interface.

Page 6: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Object Vs. Class Adapters Difference between Object Adapters and Class Adapters

As Object Adapter uses composition it can not only adapt an adaptee class, but any of its subclasses. It is flexible.

Class Adapter is committed to only one adaptee. But again it has an advantage as no need to implement the entire adaptee. It can just override the behaviour of adaptee 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 adaptee. 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 (sematics). 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 adaptee is not needed.

Page 7: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Adaptor - Case Study

Client only understands the SquarePeg interface 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.

Page 8: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Adaptor - Class Diagram

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 adaptee using the adaptee interface

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

Page 9: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Reference Class Diagram

Page 10: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Adaptor - Where To Use

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 IssuesHow much adapting should be done?

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

Totally different set of operations

Page 11: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Adaptor - Real World Example

Before Java’s new collection classes, iteration over a collection occurred via java.util.Enumeration

hasMoreElements() : booleannextElement() : Object

With the collection classes, iteration was moved to a new interface: java.util.Iterator

hasNext(): booleannext(): Objectremove(): void

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

Page 12: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Bridge Pattern

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

Page 13: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Bridge - Case Study

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 System).

In this scenario there are two interface

a) Application layer – End client interactb) Persistence layer – Interface define persist/fetch

Page 14: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Bridge - Class Diagram

Page 15: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Reference Class Diagram

Page 16: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Bridge - Where To Use

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

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

Page 17: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Template Pattern

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.

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

Page 18: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Template - Case Study

Application for processing flat file for a) Stock and b) Derivatives. Requirement

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.

Page 19: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Template Class Diagram

Page 20: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Reference Class Diagram

Page 21: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Template - Where To Use

Want to have control over algorithm to avoid duplicate code

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

Real World Example: Servlet (explained next slide)

Java – Arrays sort, mergeSort (Refer Head First Book)

JFrame – update() (Refer Head First Book)

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

Struts - RequestProcessor

Page 22: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Template - Real World Example

Servlet Life Cycle init() service() destroy()

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

Template - 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 modification.

Page 23: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Strategy Pattern

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

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

Subclasses decide how to implement steps in an algorithm.

Page 24: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Strategy - Case Study

Application for processing flat file for a) Stock and b) Derivatives. Requirement

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 Bloomberg

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

customer

Page 25: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Make it simple

Operation: Validate - common method to validate File

format/type (independent of investment type – Stock/Derivative)

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

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

Page 26: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Strategy - Class Diagram

Page 27: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Reference Class Diagram

Page 28: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Strategy - Where to use

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

Page 29: By Shishir Kumar Contact: Shishirroy2000@gmail.com

Benefits and Liabilities

Benefits 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 behavior Liabilities

Increases the number of objects All algorithms must use the same Strategy

interface