Dimit Chadha Java Technical Architect
Dimit Chadha Java Technical Architect
Dimit Chadha Java Technical Architect
Forces
Solution
Benefits Consequences
Related Patterns
Pattern is a best practice solution to
a common recurring problem
Typical solution to the problem
Design Pattern
Global architecture
OO architecture
ORB
Enterprise architecture Subsystem
System architecture
Application architecture
Frameworks
Macro-architecture
Design patterns
Micro-architecture
Objects
OO programming
Patterns Vs “Design”
Patterns Vs “Architecture”
Item Description
Generic structure A standard diagram that shows a typical structure for the
pattern
structure of a class
Structural
Creational
Constructing objects
Behavioral
object behavior
Design Patterns
Creational Design Patterns
• Make the system independent of how objects are created, composed &
represented
• Abstract the instantiation process
• Encapsulate the knowledge about concrete classes system uses
• Hide how instances of these classes are created and assembled
• Govern the what, when, who, and how of object creation
Factory
Builder Prototype
Abstract Creational
Patterns Singleton
Factory
9
Single Ton Pattern
Intent:
Ensure a class only has one instance, and provide a global point of access to it.
Examples : System. in, System. out, AWT Thread
Implementation
UML Diagram
Factory Pattern
Intent: Define an interface for creating an object, but let subclasses decide which class to
instantiate.
Factory Method lets a class defer instantiation to subclasses.
Motivation:
A database system needs to support multiple database drivers. The application can
connect to different databases at runtime based on different driver and can anticipate
which class will represent the connection. Eg JDBC DriverManager.getConnection
Applicability:
• Class can’t anticipate the class of the object it must create
• A class wants it subclass to specify the object it creates
• Classes delegate responsibility to one of several helper subclasses, and you want to
localize the knowledge of which helper subclass is the delegate.
Practical Example
Suppose we have capture data from the database (which is nothing but the list of
financial tx). Our object ive is to write this data into different finanacial tx formats like
MT103,SAP,SIF etc depending upon on the user selection.
The Simplest way (with out any desigjn pattern ) is to write some code like this :
if (fileFormat.equalsIgnoreCase(“sap")) {
parser = new xml();
} else if (fileFormat.equalsIgnoreCase("sif")) {
parser = new Sif();
}else if (fileFormat.equalsIgnoreCase(“mt103")) {
parser = new Mt103();
}
else {
throw new IllegalArgumentException("No parser for file format");
}
But this looks like a very bad design as all is managed by the main class.
A wonderful way of doing this is to pass the processing the factory…
Motivation: The system needs to read and write data to an underlying operating
system. The problem is that each operating system handles I/O differently. Need a
solution that allows the “handler” to be changed
Applicability:
• The algorithm for creating a complex object should be independent of the parts that
make up the object and how they’re assembled
• The construction process must allow different representations for the object that’s
constructed
The Builder pattern separates the construction of a complex object from its representation, so
that the same construction process can create different representation.
Practical Example
This pattern is used by fast food restaurants to construct children's meals. Children's meals
typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, coke,
and toy car). Note that there can be variation in the contents of the children's meal, but the
construction process is the same.
Whether a customer orders a cheeseburger, or chicken, the process is the same. The employee
at the counter directs the crew to assemble a main item, side item, and toy. These items are
then placed in a bag. The drink is placed in a cup and remains outside of the bag. This same
process is used at competing restaurants.
Also used to save the data captured from the web form & then use that data as per the
requirement s. Here process of creating the builder is same but how we use the contents of
the builder is as per requirement
Structural Patterns
Help identify and describe relationships between entities
Address how classes and objects are composed to form large structures
• Class-oriented patterns use inheritance to compose interfaces or implementations
• Object-oriented patterns describe ways to compose objects to realize new
functionality, possibly by changing the composition at run-time
Facade
Decorator Bridge
Flyweight Adapter
Proxy
19
AdapterPattern
Intent: Convert the interface of a class into another interface clients expect. Adapter lets
classes work together that couldn't otherwise because of incompatible interfaces.
Motivation: Two entities want to work together but there is an interface mismatch.
Changing one interface to support the other would create a tight coupling. Need to wrap
one interface so it supports the interactions.
Applicability:
• Want to use an existing class and its interface does not match
• Want to create a reusable class that cooperates with unrelated classes
The Adapter pattern allows otherwise incompatible classes to work together by converting the
interface of one class into an interface expected by the clients.
Practical Example:
In the US, electrical outlets are three-pronged. When traveling to certain countries in
Europe, electrical outlets require 2-prongs. To make US electronics work in Europe you can
get a set of adapters to create compliance between the two interfaces.
public interface IRoundPeg { public interface ISqaurePeg {
public void insertIntoHole(String msg); public void insertSquare(String msg);
} }
public class RoundPeg implements IRoundPeg{
public void insertIntoHole(String msg) {
System.out.println("RoundPeg insertIntoHole(): " + msg);
}
}
}
public class TestPegs {
public static void main(String[] args) {
SquarePeg squarePeg = new SquarePeg();
squarePeg.insertSquare("Inserting square peg...");
RoundPeg roundPeg = new RoundPeg();
roundPeg.insertIntoHole(“inserting hole peg”);
PegAdapter adapter = new PegAdapter(roundPeg);
adapter.insertSquare("Inserting round peg...");
}
}
Output will be :
UML Diagram
DecoratorPattern
Intent: Attach additional responsibilities to an object dynamically. Decorators provide a
flexible alternative to sub classing for extending functionality, without breaking the
interface.
Motivation:
A system needs to provide consistent ability to read and write information across operating
systems. It needs to support different approaches to write the data, the most primitive
being binary.
Applicability:
• Add responsibilities to individual objects dynamically and transparently, that is, without
affecting other objects.
• When extension by sub classing is impractical
Although paintings can be hung on a wall with or without frames, frames are often added, and
it is the frame which is actually hung on the wall. Prior to hanging, the paintings may be matted
and framed, with the painting, matting, and frame forming a single visual component.
Java’s IO capabilities
public interface IComponent { public class Component implements IComponent{
public void doStuff(); public void doStuff() {
} System.out.println("Do Suff");
}
}
IComponent component;
}
public class DecoratorClient {
public static void main(String[] args) {
IComponent comp = new Component();
Decorator decorator = new ConcreteDecorator(comp);
decorator.doStuff();
}
Result :
Do Suff
Decorator does some stuff too
Decorator
addedBehavior()
Icomponent
(doStuff)
FaçadePattern
Intent: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a
higher-level interface that makes the subsystem easier to use. Doesn't exposing details to
the clients. The Facade defines a unified, higher level interface to a subsystem, that makes it
easier to use.
Example:
Consumers encounter a Facade when ordering from a catalog. The consumer calls one number
and speaks with a customer service representative. The customer service representative acts as
a Facade, providing an interface to the order fulfillment department, the billing department,
and the shipping department.
public interface Store { public class FinishedGoodsStore implements Store {
public Goods getGoods(); public Goods getGoods() {
} FinishedGoods finishedGoods = new FinishedGoods();
return finishedGoods;
}
}
RealSubject Implementation, which is the concrete and heavyweight implementation of the image
interface. The High resolution image, loads a high resolution image from disk, and renders it to screen
when showImage() is called.
Applicability:
• You want to represent part-whole hierarchies of objects
• You want clients to be able to ignore the difference between compositions of objects &
individual objects. Clients will treat all objects in the composite structure uniformly.
Example:
Arithmetic expressions are Composites. An arithmetic expression consists of an operand, an
operator (+ - * /), and another operand. The operand can be a number, or another arithmetic
expression. Thus, 2 + 3 and (2 + 3) + (4 * 6) are both valid expressions.
Bridge Pattern
Intent: Decouple (separate) an object’s abstraction from its implementation so the two can
vary independently
Motivation: The typical way to deal with several possible implementations of an
abstraction is through inheritance. However, this may bind an implementation to an
abstraction, making it hard to extend, re-use, or modify.
Applicability:
• You want to avoid a permanent binding between an abstraction and its implementation
• The abstractions and their implementations should be extensible by sub classing
• Changes in the implementation of an abstraction should have no impact on clients; that
is, their code should not have to be recompiled.
A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. The
purpose of the switch is to turn a device on or off. The actual switch can be implemented as a
pull chain, a simple two position switch, or a variety of dimmer switches.
35
Chain of
Responsibility
Visitor Command
Template
Interpreter
Method
Behavioral
Strategy Patterns Iterator
State Mediator
Observer Memento
CommandPattern
Intent: Encapsulate a request as an object, letting you parameterize clients with different
requests
Motivation: You need to be able to change the implementation of an operation
dynamically, at run-time by specifying an operation as an object
Applicability:
Decouple implementation of operation
Creation consistent action structure
First thing is the Order. The order is made of command which the customer gives the
waiter.
Now, here, the waiter takes command and wraps it in an order, the order is associated to
a particular customer. For, the cook, the order is associated to a cook and also Food is
associated to the Order.
The order is an object which depends on the command. The food item will change as
soon as the command changes. This is loose-coupling between the client and the
implementation.
ObserverPattern
Intent: Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically
Applicability:
When a change to one object requires changing others, and you don't know how many
objects need to be changed.
When an object should be able to notify other objects without making assumptions
about who these objects are
" Some auctions demonstrate this pattern. Each bidder possesses a numbered paddle
that is used to indicate a bid. The auctioneer starts the bidding, and "observes“ when a
paddle is raised to accept the bid. The acceptance of the bid changes the bid price, which
is broadcast to all of the bidders in the form of a new bid.
StrategyPattern
Intent: Define a family of algorithms, encapsulate each one, and make them
interchangeable.
A Strategy defines a set of algorithms that can be used interchangeably.
Motivation: A system needs to change how it connects to the web depending on the
underlying security within an organization. It may be able to connect directly, use a
proxy, or require security.
Applicability:
You need different variants of an algorithm.
Application construction
! " Applications built by many groups of developers
! " Groups have different skills
! " Groups have different objectives
! " Groups have different timelines
! " This translates into various pieces of the application being developed independently
Front Controller
View Helper
Composite View
Business Delegate
Dispatcher View
Service To Worker
FrontController
The “front door” to your application
Generally a pre-processor, but can be used for post processing too
! " Often used to enforce
! " Validation rules
! " Authentication constraints
! " Dispatching of requests
! " Session management
Advantages
Promotes reuse of common code that is needed for all
requests .
Promotes flexibility
Easier to maintain
Business Delegate
! " Used to provide a façade over a complex business tier
! " Normally, presentation components interact with business
services directly, which may cause problems
! " If the business tier API changes, it affects the presentation tier
! " Heavy interaction with the business tier may result in too many
network calls
! " A Business Delegate can perform caching and throttling
Business Delegate as a Proxy
! " The Business Delegate exposes the same interface as the business tier
! " Calls to the Business Delegate can be forwarded to the business tier
! " Data can also be cached and calls short-circuited
! " This can reduce network calls and increase performance
Business Delegate as an Adapter
! " Excellent for communication with disparate business components
! " For example, communication with a web service component could be
accomplished
! " The delegate would parse the XML request
! " The data in the request could be sent to an existing, non-XML aware, business
tier
! " A response could work the same way
Dispatcher View
The web server (Apache, WEBrick, etc.) receives the request. It uses routes to find out which
controller to use: the default route pattern is “/controller/action/id” as defined in configuration file.
The web server then uses the dispatcher to create a new controller, call the action and pass the
parameters.
Controllers do the work of parsing user requests, data submissions, cookies, sessions and the
“browser stuff”.
Models are PHP classes. They talk to the database, store and validate data, perform the business
logic and otherwise do the heavy lifting.
Views are what the user sees: HTML, CSS, XML, JavaScript, JSON. They’re the sales rep putting up
flyers and collecting surveys, at the manager’s direction. Views are merely puppets reading what the
controller gives them. They don’t know what happens in the back room.
The controller returns the response body (HTML, XML, etc.) & metadata (caching headers, redirects)
to the server. The server combines the raw data into a proper HTTP response and sends it to the user.
Model VIEW CONTROLLER
The pattern isolates "domain logic" (the application logic for the user) from input and presentation (UI),
permitting independent development, testing and maintenance of each.
The model is used to manage information and notify observers when that information changes. The model is the
domain-specific representation of the data upon which the application operates. Domain logic adds meaning to
raw data (for example, calculating whether today is the user's birthday, or the totals, taxes, and shipping charges
for shopping cart items). When a model changes its state, it notifies its associated views so they can be refreshed.
Many applications use a persistent storage mechanism such as a database to store data. MVC does not
specifically mention the data access layer because it is understood to be underneath or encapsulated by the
model. Models are not data access objects; however, in very simple apps that have little domain logic there is no
real distinction to be made. Active Record is an accepted design pattern which merges domain logic and data
access code - a model which knows how to persist itself.
The view renders the model into a form suitable for interaction, typically a user interface element. Multiple views
can exist for a single model for different purposes. A viewport typically has a one to one correspondence with a
display surface and knows how to render to it.
The controller receives input and initiates a response by making calls on model objects. A controller accepts input
from the user and instructs the model and viewport to perform actions based on that input.
An MVC application may be a collection of model/view/controller triplets, each responsible for a different UI
element.
MVC is often seen in web applications where the view is the HTML or XHTML generated by the app. The
controller receives GET or POST input and decides what to do with it, handing over to domain objects (i.e. the
model) that contain the business rules and know how to carry out
specific tasks such as processing a new subscription.
MVC web application frameworks:
Aranea
Cocoon
Induction
JSF
Makumba Web development framework in the form of JSP Tag Library and Java API that is based on
MVC, but willingly breaks it
Oracle Application Framework
Play Framework
PureMVC, a framework for Java
Sling, used to create content based applications on top of JCR. Supported scripting languages are
JSP, server-side JavaScript, Ruby, Velocity
Spring MVC Framework
Struts
Struts2
Stripes
Tapestry
Wavemaker, a WYSIWYG development platform for Ajax web applications.[7]
WebObjects
WebWork
Wicket
Web Dynpro Java
Service Locator Pattern
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, and improve performance by providing a caching facility.