3. Agenda
• What is Design Pattern?
• History of Design Pattern.
• Elements of Design pattern.
• JAVA and J2EE Patterns.
• Design Pattern Categories
• Classification of GOF patterns
• Creational Pattern – Factory Method, Abstract Factory, Builder,
Prototype, Singleton
• Structural Pattern – Adapter, Decorator , Bridge, Composite,
Proxy, Facade, Flyweight
• Behavioural Pattern – Command, Visitor, Observer, Chain of
Responsibility, Iterator, Mediator, Strategy, Template Method,
State pattern, Memento, Interpreter
• Conclusion
3
4. What is Design Pattern?
• A design pattern is a general reusable solution to commonly
occurring problem in software design.
• It is a description or template for how to solve problem that can
be used in many different situations.
• Problems are addressed without rediscovering solution from
scratch.
Analogy:
Creating a new movie story by taking best part of stories or jokes
scenes from past released movies or movies of other languages.
4
5. History of Design Pattern
• Patterns are originated as an architectural concept by
Christopher Alexander -1977.
• Knet Beck and Ward Cunningham began experimenting ideas of
applying patterns into programming -1987
• Design pattern gained a popularity , when GOF(Gang of Four)
book: written by Enrich Gamma,Richard Helm, Ralph
Johnson,John vlissides
Design Patterns: Elements of Reusable Object-Oriented Software
published in year-1994.
Nowadays, These GOF patterns usually considered as de-facto
standard to follow.
5
6. Elements of Design Pattern
• Pattern Name
– Increases design vocabulary, higher level of abstraction
• Problem
– When to apply the pattern
– Problem and context, conditions for applicability of pattern
• Solution
– Relationships, responsibilities, and collaborations of design elements
– any concrete design or implementation, rather a template
• Consequences
– Results and trade-offs of applying the pattern
– Space and time trade-offs, reusability, extensibility, portability
6
9. 13.Transaction Patterns
ACID Transaction, Composite Transaction, Two-Phase Commit, Audit Trail
14.Distributed Architecture Patterns
Shared Object, Object Request Broker, Object Replication, Redundant
Independent Objects, Prompt Repair, Mobile Agent, Demilitarized Zone,
Process Pair
15. Distributed Computing Patterns
Object Identifier, Registry, Protection Proxy, Publish-Subscribe, Retransmission,
Mailbox ,Heavyweight/Lightweight Object,Heartbeat,Connection Multiplexing.
16. Temporal Patterns
Time Server,Versioned Object, Temporal Property
17.Database Patterns
Persistence Layer,CRUD,Stale Object,Type Conversion,isDirty,Lazy Retrieval
18.J2EE Patterns
1. Presentation Tier Patterns:-
Intercepting Filter, Front Controller, Context Object, Application
Controller, View Helper, Composite View, Service to Worker,Dispatcher View.
2. Business Tier Patterns:-
Business Delegate, Service Locator, Session Facade, Application Service, Business
Object, Composite Entity, Transfer Object, Transfer Object Assembler Value
List Handler.
3.Integration Tier Patterns:-
9
10. Design Pattern Categories:
• Creational
-Abstracts the instantiation process
-Dynamically create objects so that they don’t have to be
instantiated
-The basic form of object creation could result in design
problems or added complexity to the design. Creational design
patterns solve this problem by somehow controlling this object
creation .
• Structural
-Composes groups of objects into larger structure
- Structural patterns are concerned with how classes and objects
are composed to form larger structure. It uses inheritance to
compose interface or implementations
• Behavioral
- Defines communication among objects in a given System
- Provides better control of flow in complex application
10
12. Classification of GOF Pattern
Purpose
Creational Structural Behavioral
Scope Class Factory Method Adapter (class) Interpreter
Template Method
Object Abstract Factory
Builder
Prototype
Singleton
Adapter (object)
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Chain of
Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
12
Defer object creation to
another class
Defer object creation to
another object
Describe Ways to Assemble Objects
Describe Algorithms and flow control
13. Creational Pattern:
• Abstract Factory
-provides an interface for creating related objects without
specifying their concrete classes
• Builder
-Reuses the construction process of a complex object
• Factory Method
- Let’s subclasses decide which class to instantiate from defined
interface
• Prototype
- Creates new objects by copying a prototype
• Singleton
- Ensures a class has only one instance with global point of access
it
13
14. Structural Pattern
• Adapter
-Converts the interface of one class to an interface of another
• Bridge
- Decouples abstraction from its implementation
• Composite
- Compose objects into tree structures to represent hierarchies
• Decorator
- Attach responsibilities to an object dynamically
• Façade
- Provide unified interface to set of interfaces
• Flyweight
- Supports large number of fine grained objects by sharing
• Proxy
- Provide a surrogate for another object to control access to it
14
15. Behavioral Pattern
• Chain of Responsibility
- passes a request along a chain of objects until the appropriate
one handles it
• Command
- Encapsulate a request as an object
• Interpreter
- Defines a representation and an interpreter for a language
grammer
• Iterator
- Provides a way to access elements of an object sequentially
without exposing its implementation
• Mediator
-Defines an object that encapsulates how set of objects interact
15
16. • Memento
- Captures an object’s internal state so that it can be later
restored the state if necessary
• Observer
- Defines one-to-many dependency among objects
• State
- Allows an object to alter its behavior when its internal state
changes
• Strategy
- Encapsulates a set of algorithms individually and makes them
interchangeable.
• Template Method
- Lets subclasses redefine certain steps of algorithm
• Visitor
- Defines a new operation without changing the classes on which
it operates
16
18. Abstract Factory Pattern:
Definition:
Provide an interface for creating families of related or
dependent objects without specifying their concrete classes.
Analogy:
In Indian great epics, we know kauravas and Pandavs fight for Hastinapur in
Kurkshethra war field. when kurkshaethra war is declared any other kings such as
Krishna, Bhisma, Dhronacharya so on want to support in war irrespective of blood
relationship either they can support kauravas or Pandavs in the war. As a result,
Bhisma , Krupacharya, Dhronacharya eventhough they like Pandavs but due to
restriction of ethics they forced to join kauravas without any choice. They fight
for kauravas and Krishna takes Pandavas side. It means no hybrid behavior in the
or part of support so on. If same analogy followed, Abstract factory can be used
if there is clear categories or classification of objects only one set of objects will
be executed and there is nothing as such so called hybrid category or group.
18
20. Implementation
AbstractFactory.java
package com.designpattern.learning.abstractfactory;
public interface AbstractFactory {
AbstractProductA createProductA();
AbstractProductB createProductB();
}
ConcreteFactory1.java
package com.designpattern.learning.abstractfactory;
public class ConcreteFactory1 implements AbstractFactory {
public AbstractProductA createProductA() { return new ProductA1(); };
public AbstractProductB createProductB() { return new ProductB1(); };
}
ConcreteFactory2.java
package com.designpattern.learning.abstractfactory;
public class ConcreteFactory2 implements AbstractFactory
{
public AbstractProductA createProductA() { return new ProductA2(); };
public AbstractProductB createProductB() { return new ProductB2(); };
}
20
21. AbstractProductA.java
package com.designpattern.learning.abstractfactory;
public interface AbstractProductA
{
public void createProductA();
}
AbstractProductB.java
package com.designpattern.learning.abstractfactory;
public interface AbstractProductB {
public void createProductB();
}
ProductA1.java
package com.designpattern.learning.abstractfactory;
public class ProductA1 implements AbstractProductA {
public void createProductA() {
System.out.println("ProductA1");
}
}
21
22. ProductA2.java
package com.designpattern.learning.abstractfactory;
public class ProductA2 implements AbstractProductA {
public void createProductA() {
System.out.println("ProductA2");
}
}
ProductB1.java
package com.designpattern.learning.abstractfactory;
public class ProductB1 implements AbstractProductB {
public void createProductB() {
System.out.println("ProductB1");
}
}
ProductB2.java
package com.designpattern.learning.abstractfactory;
public class ProductB2 implements AbstractProductB {
public void createProductB() {
System.out.println("ProductB2");
}
}
22
23. package com.designpattern.learning.abstractfactory;
public class TestAbstractFactory {
public static void main( String arg[] ){
try {
AbstractFactory factory = new ConcreteFactory1();
AbstractProductA productA = factory.createProductA();
productA.createProductA();
AbstractProductB productB = factory.createProductB();
productB.createProductB();
factory = new ConcreteFactory2();
productA = factory.createProductA();
productA.createProductA();
productB = factory.createProductB();
productB.createProductB();
}catch( Exception e ){
e.printStackTrace();
}
}
}
23
24. Applicability:
• System should be independent of how its product is created,
composed and represented
• A System should be configured with one of multiple families
product
• A family of related product objects to be designed to used
together and you need to enforce this constraint
• You want to reveal the class library of product and you want to
reveal just their interfaces not their implementation.
Advantages:
• It isolates concrete classes because a factory encapsulates the
responsibility and process of creating product objects
-Isolates clients from implementation classes
• It promotes consistency among product since the application is
using objects from only one family at a time.
24
25. Disadvantages:
• Extending the abstract factory is not easy because abstract
factory interface fixes the set of products to be created. To
introduce new product may require extra effort to change
abstract factory and all its subclasses.
• JAVA-CORE –LIBRARIES Examples
– javax.xml.parsers.DocumentBuilderFactory#newInstance()
– javax.xml.transform.TransformerFactory#newInstance()
– javax.xml.xpath.XPathFactory#newInstance()
25
26. Factory Method Pattern
Definition : Define an interface for creating an object, but let
subclasses decide which class to instantiate. Factory Method lets
a class defer instantiation to subclasses
In simple words, if we have a super class and n sub-classes, and
based on data provided, we have to return the object of one of
the sub-classes, we use a factory pattern.
Analogy:
The Factory Method implies a preplanned at the factory level. Assume your family
wants plan for summer holiday’s. so there are several packages offered by travel
portal, we may be forced to choice one of the available holiday trip package. The
travel agency(factory class) has set of packages(factory method) but you will
book one of the available package before you go for the trip. so as per analogy
travel agency has set packages as factory method. You will be selecting one of the
available package based on your feasible requirement, time and cost. As a result
only one package object available and executed and which is dictated by Travel
Agency. So Travel agency would be class has set of Package object. As per
parameterized your feasible choice of package , the package object trip will be
pre-created and executed.
26
28. Implementation
FactoryPattern:
package com.designpattern.learning.factorypattern;
public class FactoryPattern {
protected String type;
FactoryPattern(String type){
this.type = type;
}
public Connection createConnection(){
if(type.equals ("Oracle")){
return new OracleConnection();
}else if(type.equals("SQLServer")){
return new SQLServerConnection();
}else {
return new MySQLServerConnection();
}
}
}
28
29. Connection:
package com.designpattern.learning.factorypattern;
public abstract class Connection {
public Connection(){
}
public abstract String description();
}
MySQLServerConnection:
package com.designpattern.learning.factorypattern;
public class MySQLServerConnection extends Connection{
public MySQLServerConnection(){
}
public String description(){
return "My SQL Server";
}
}
OracleConnection:
package com.designpattern.learning.factorypattern;
public class OracleConnection extends Connection{
public OracleConnection(){
}
public String description(){
return "Oracle";
}
}
29
30. SQLServerConnection :
package com.designpattern.learning.factorypattern;
public class SQLServerConnection extends Connection{
public SQLServerConnection(){
}
public String description(){
return "SQL Server";
}
}
TestFactoryPattern:
package com.designpattern.learning.factorypattern;
public class TestFactoryPattern {
public static void main (String args []) {
FactoryPattern factoryPattern;
//oracle
factoryPattern = new FactoryPattern("Oracle");
Connection connection = factoryPattern.createConnection();
System.out.println("Connected to:"+ connection.description());
}
}
30
31. Applicability
• When a class wants its subclasses to specify the objects to
creates
• Classes delegate responsibility to one of several helper
subclasses, and you want to localize the knowledge of which
helper subclasses is the delegate
Advantages:
• Eliminates the needs to bind application classes into your code.
The code deals with interfaces so it can work with any classes
that implement a certain interface.
• Enables the subclasses to provide an extended version of an
object, because creating an object inside a class is more flexible
than creating an object directly in the client
31
32. Disadvantage
Clients might have to subclass the creator class just to create a
particular Concrete Product object
JAVA-CORE –LIBRARIES Examples
– java.util.Calendar#getInstance()
– java.util.ResourceBundle#getBundle()
– java.text.NumberFormat#getInstance()
– java.nio.charset.Charset#forName()
– java.net.URLStreamHandlerFactory#createURLStreamHandler(String)
(Returns singleton object per protocol)
– java.util.EnumSet#of()
– javax.xml.bind.JAXBContext#createMarshaller() and other similar methods
32
33. Builder Pattern
• Definition: Separates the construction of a complex object from
its representation so that the same construction process can
create different representations.
• Analogy: Customer request a contractor for building House or
Apartment, builder (contractor) know how to build apartment or
house. He does complex construction process(common ready made
process). After completion of building activity, he handover the
house or apartment to customer. construction of house or
apartment is a step by step process, finally customer gets house
or apartment as final product.
34. Class diagram
Participants
Builder.
specifies an abstract interface for creating parts of a Product object
ConcreteBuilder.
constructs and assembles parts of the product by implementing the Builder interface
defines and keeps track of the representation it creates
provides an interface for retrieving the product
Director.
constructs an object using the Builder interface
Product.
represents the complex object under construction. ConcreteBuilder builds the product's
internal representation and defines the process by which it's assembled
includes classes that define the constituent parts, including interfaces for assembling
the parts into the final result
35. Implementation:
package com.learning.designpattern.BuilderPattern;
class Contractor {
IHouse buildHouse (String type){
if(type.equals("APARTMENT")){
return new Apartment();
}else{
return new IndividualHouse();
}
}
}
interface IHouse{
public abstract String doArchitecture();
public abstract String doPurchaseOfMaterial();
public abstract String doRooms();
public abstract String doFloors();
public abstract String doPainting();
public abstract String getConstructedHome();
}
36. Implementation
class Apartment implements IHouse{
Apartment(){
}
public String doArchitecture(){
return "Completed Sketch of Apartment";
}
public String doPurchaseOfMaterial(){
return"Purchased Apartment Materials";
}
public String doRooms(){
return"Constructed Rooms";
}
public String doFloors(){
return"Constructed Floors requested";
}
public String doPainting(){
return"Completed Apartment Painting";
}
public String getConstructedHome(){
String str = null;
str = str + doArchitecture()+"n";
str = str + doPurchaseOfMaterial()+"n";
str = str + doFloors()+"n";
str = str + doRooms()+"n";
str = str + doPainting()+"n";
return str;
}
}
37. class IndividualHouse implements IHouse{
IndividualHouse(){
}
public String doArchitecture(){
return "Completed Sketch of House";
}
public String doPurchaseOfMaterial(){
return"Purchased House Materials";
}
public String doRooms(){
return"Constructed Rooms";
}
public String doFloors(){
return"Constructed Floors requested";
}
public String doPainting(){
return"Completed House Painting";
}
public String getConstructedHome(){
String str = null;
str = str + doArchitecture()+"n";
str = str + doPurchaseOfMaterial()+"n";
str = str + doFloors()+"n";
str = str + doRooms()+"n";
str = str + doPainting()+"n";
return str;
}
}
38. public class Client{
public static void main(String args[]){
Contractor contractor = new Contractor();
System.out.println ("Construction of Apartment");
IHouse apartment = contractor.buildHouse("APARTMENT");
System.out.println (apartment.getConstructedHome());
System.out.println("Construction of House");
IHouse house = contractor.buildHouse("House");
System.out.println (house.getConstructedHome());
}
}
Applicability:
• The algorithm for creating a complex object should be independent of both the parts
that make up the object and how the parts are assembled.
•The construction process must allow different representations of the constructed object
Advantages:
•When you want to vary product's internal representation.
•Gives greater control over construction process.
•Isolates code from construction and representation.
39. JAVA-CORE –LIBRARIES Examples
•java.lang.StringBuilder#append() (unsynchronized)
•java.lang.StringBuffer#append() (synchronized)
•java.nio.ByteBuffer#put() (also on CharBuffer, ShortBuffer,
IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
•javax.swing.GroupLayout.Group#addComponent()
•All implementations of java.lang.Appendable
40. Prototype:
Definition : Specify the kinds of objects to create using a
prototypical instance, and create new objects by copying this
prototype.
The prototype means making a clone. This implies cloning of an
object to avoid creation. If the cost of creating a new object is
large and creation is resource intensive, we clone the object. We
use the interface Cloneable and call its method clone() to clone
the object
Analogy:
Suppose you are a brickmaker. You use a mold (a prototype) for
packing your stomped and mized mud and straw into for cloning a
pile of identical bricks. But one day, someone invented chemical
mortar, which sets up a lot faster and eliminates the need for
mixing mud and straw. You can still use your same brick-making
mold, but you can now eliminate the methods for the whole mud-
and-straw stomping ritual.
40
41. When a user asks for information for a certain product the
application could gather that information in two ways:
• execute the complex query against legacy database, gather the
information, and instantiate the object.
• instantiate the objects at predefined intervals and keep them in
a cache, when an object is requested, it is retrieved from cache
and cloned. When the legacy database is updated, discard the
content of the cache and re-load with new objects
42. Class Diagram:
Participants:
Prototype
declares an interface for cloning itself.
ConcretePrototype.
implements an operation for cloning itself.
Client.
creates a new object by asking a prototype to clone itself
44. public String getDescription() {
return description;
}
public void setDescription (String description) {
this.description = description;
}
class Book extends Product {
private int numberOfPages;
public int getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages (int i) {
numberOfPages = i;
}
}
class DVD extends Product {
private int duration;
public int getDuration() {
return duration;
}
45. public void setDuration (int i) {
duration = i;
}
}
class ProductCache{
private static Hashtable <String,Product> queryCache = new Hashtable<String,Product>();
public static void loadCache(){
Book b1 = new Book();
b1.setDescription("JAVA");
b1.setNumberOfPages(100);
b1.setProductCode("Prod1");
queryCache.put((String)b1.getProductCode(),(Product) b1);
DVD dvd1 = new DVD();
dvd1.setDescription("TITANIC");
dvd1.setDuration(60);
dvd1.setProductCode("Prod3");
queryCache.put(dvd1.getProductCode(), dvd1);
public static Product getProduct (String productCode){
Product product = (Product) queryCache. get(productCode);
return (Product) product.clone();
}
}
45
47. Applicability:
• When the classes to instantiate are specified at run time.
• When you want to avoid building a class hierarchy of factories
that parallels the class hierarchy of products.
• When instances of a class can have one of only a few
combinations of state.
Advantages:
• Adding and removing products at runtime.
• Specifying new objects by varying values.
• Specifying new objects by varying structure.
• Reduced subclassing.
• Configuring an application with classes dynamically
47
48. Disadvantages:
• Each subclass of prototype must implement the clone operation,
which may be difficult
• JAVA-CORE –LIBRARIES Examples
– java.lang.Object#clone() (the class has to implement java.lang.Cloneable)
48
49. Singleton
Definition: Ensure a class only has one instance, and provide a global
point of access to it.
Java has several design patterns Singleton Pattern being the
most commonly used. Java Singleton pattern belongs to the
family of design patterns, that govern the instantiation process.
This design pattern proposes that at any time there can only be
one instance of a singleton (object) created by the JVM.
Analogy : Singleton can be used of connection pooling, printer pool,
logger so on, wherever we need to create only single instance.
49
50. Class diagram:
Participants:
– defines an Instance operation that lets clients access its unique instance.
– responsible for creating and maintaining its own unique instance
50
51. Implementation:
package com.learning.designpattern.SingletonPattern;
import java.io.PrintStream;
class LogManager {
private java.io.PrintStream m_out;
private LogManager (PrintStream out ){
m_out = out;
}
public void info( String msg ){
System.out.println( msg );
}
static private LogManager sm_instance;
static public LogManager getInstance (){
if ( sm_instance == null )
sm_instance = new LogManager( System.out );
return sm_instance;
}
}
51
52. public class SingletonDemo {
public static void main(String args[]){
LogManager logger = LogManager.getInstance();
logger.info("Welcome to logger info");
logger.info("Process Started");
logger.info("Process Completed");
}
}
52
53. When there must be only one instance of a class.
Advantages:
– Controlled access to unique instance.
– Reduced name space.
– Allows refinement of operations and representations.
– Permits a variable number of instances.
– More flexible than class operations
53
Applicability:
JAVA-CORE –LIBRARIES Examples
java.lang.Runtime#getRuntime()
java.awt.Desktop#getDesktop()
java.lang.System#getSecurityManager()
55. Adapter Pattern
Definition:
Adapters are used to enable objects with different interfaces to
communicate with each other.
The Adapter pattern is used so that two unrelated interfaces can
work together. The joining between them is called an Adapter.
This is something like we convert interface of one class into
interface expected by the client. We do that using an Adapter.
Analogy:
We all have electric sockets in our houses of different sizes and
shapes. I will take an example of a socket of 15 Ampere. This is a
bigger socket and the other one which is smaller is of 5 Ampere.
A 15 Amp plug cannot fit into a 5 Amp socket. Here, we will use an
Adapter. The adapter can be called a connector here. The
connector connects both of these and gives output to the client
plug which is of 5 Amp.
55
56. Class diagram:
• Adapters come in two flavors, object adapters and class adapters.
These two methods embody the difference between the use of
inheritance and composition to solve problems.
(By composition) (By Inheritance)
56
57. Implementation (By composition)
Client.java
package com.designpattern.learning.adapterpattern;
public class Client {
public static void main (String args[]){
FirstObject fo = new FirstObject();
fo.setName ("Mallikarjuna Govind");
AdapterObject ao = new AdapterObject(fo);
System.out.println ("first name::“ +ao.getFirstName());
System.out.println ("last name::“ +ao.getLastName());
}
}
package com.designpattern.learning.adapterpattern;
public class FirstObject implements FirstObjectInteface{
private String name;
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
• } 57
58. package com.designpattern.learning.adapterpattern;
public interface FirstObjectInteface {
public String getName();
public void setName (String name);
}
package com.designpattern.learning.adapterpattern;
public interface SecondObjectInterface {
public String getFirstName();
public void setFirstName(String first Name);
public String getLastName();
public void setLastName(String lastName);
}
package com.designpattern.learning.adapterpattern;
public class SecondObject implements SecondObjectInterface{
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
• }
58
60. public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
package com.designpattern.learning.adapterpattern;
public class Client {
public static void main (String args[]){
FirstObject fo = new FirstObject();
fo.setName ("Mallikarjuna Govind");
AdapterObject ao = new AdapterObject(fo);
System.out.println("first name::"+ao.getFirstName());
System.out.println("last name::"+ao.getLastName());
} }
60
61. Applicability:
• you want to use an existing class, and its interface does not
match the one you need.
• you want to create a reusable class that cooperates with
unrelated or unforeseen classes, that is, classes that don’t
necessarily have compatible interfaces.
• (object adapter only) you need to use several existing
subclasses, but it’s impractical to adapt their interface by
subclassing every one. An object adapter can adapt the
interface of its parent class.
Advantages:
• They handle logic by wrapping a new interface around that of an
existing class so you can use new APIs (with different
interfaces) and avoid breaking existing implementations.
• It absolutely interconnects two incompatible interfaces
61
62. Disadvantages:
• It unnecessarily increases the size of the code as class
inheritance is less used and lot of code is needlessly duplicated
between classes.
• Sometimes many adaptations are required along an adapter chain
to reach the type which is required.
• JAVA-CORE –LIBRARIES Examples
– java.util.Arrays#asList()
– java.util.Collections#list()
– java.util.Collections#enumeration()
– java.io.InputStreamReader(InputStream) (returns a Reader)
– java.io.OutputStreamWriter(OutputStream) (returns a Writer)
– javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal()
62
63. Bridge Pattern:
Definition : “Decouple an abstraction from its implementation, so
that the two can vary independently" .
The bridge uses encapsulation, aggregation, and can use
inheritance to separate responsibilities into different classes.
Analogy: Imagine two types of cars (the abstraction), a Jaguar
and a Mercedes (both are Refinements of the Abstraction). The
Abstraction defines that a Car has features such as tires and an
engine. Refinements of the Abstraction declare what specific
kind of tires and engine it has.
Finally, there are two types of road. The road is the Implementor
(see image below). A highway and an interstate highway are the
Implementation Details. Any car refinement needs to be able to
drive on any type of road; this concept is what the Bridge Pattern
is all about.
64. Class diagram:
Participants:
• Abstraction.
– defines the abstraction's interface.
– maintains a reference to an object of type Implementor.
• RefinedAbstraction.
– extends the interface defined by Abstraction.
• Implementor.
– defines the interface for implementation classes. This interface doesn't have to
correspond exactly to Abstraction's interface; in fact the two interfaces can be quite
different. Typically the Implementation interface provides only primitive operations, and
Abstraction defines higher-level operations based on these primitives.
• ConcreteImplementor.
– implements the Implementor interface and defines its concrete implementation
66. package com.learning.designpattern.BridgePattern;
//Implementation hierarchy
interface DVDPlayer{
void on();
void off();
void pause();
void stop();
}
class SonyDVDPlayer implements DVDPlayer{
public void on(){
System.out.println("SONY DVD Player is switched ON");
}
public void off(){
System.out.println("SONY DVD Player is switched OFF");
}
public void pause(){
System.out.println("SONY DVD Player is switched PAUSE");
}
public void stop(){
System.out.println("SONY DVD Player is switched STOP");
}
}
67. • class PhilipsDVDPlayer implements DVDPlayer{
public void on(){
System.out.println("Philips DVD Player is switched ON");
}
public void off(){
System.out.println("Philips DVD Player is switched OFF");
}
public void pause(){
System.out.println("Philips DVD Player is switched PAUSE");
}
public void stop(){
System.out.println("Philips DVD Player is switched STOP");
}
}
//abstraction hierarchy
interface DVDPlayerRemoteControl{
void on();
void off();
void pause();
void stop();
}
68. class DVDPlayerRemoteControlImpl implements DVDPlayerRemoteControl{
private DVDPlayer dvdPlayer;
DVDPlayerRemoteControlImpl (DVDPlayer dvdPlayer){
this.dvdPlayer = dvdPlayer;
}
public void on(){
dvdPlayer.on();
}
public void off(){
dvdPlayer.off();
}
public void pause(){
dvdPlayer.pause();
}
public void stop(){
dvdPlayer.stop();
}
}
69. public class Client{
public static void main(String args[]){
System.out.println("SONY:");
DVDPlayerRemoteControl player = new DVDPlayerRemoteControlImpl(new
SonyDVDPlayer());
player.on();
player.off();
player.pause();
player.stop();
System.out.println("PHILIPS:");
player = new DVDPlayerRemoteControlImpl(new PhilipsDVDPlayer());
player.on();
player.off();
player.pause();
player.stop();
}
}
70. Applicability:
– You want to avoid a permanent binding between an abstraction and
its implementation.
– Both the abstraction 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.
– You want to share an implementation among multiple objects, and this
fact should be hidden from the client
Advantages:
– The implementation of an abstraction can be configured at run-time.
– Changing an implementation class doesn’t require recompiling the abstraction
class and its clients.
– You can extend the abstraction and implementation hierarchies independently.
– Hiding implementation details from clients
71. Disadvantages:
• Increases complexity.
• Double indirection – This will have a slight impact on
performance. The abstraction needs to pass messages along to
the implementator for the operation to get executed.
• JAVA-CORE –LIBRARIES Examples
– the JDBC API (a set of interfaces such as DataSource, PooledConnection,
RowSet etc.) is typically considered as a bridge, which allows independent
implementations for different databases (such as Sybase, Oracle or other
ODBC databases)
71
72. Composite
Definition : Compose objects into tree structures to represent part-
whole hierarchies. Composite lets clients treat individual objects
and compositions of objects uniformly.
Analogy: Building Employee hierarchy , Building directory of files
may contain directives and it may goes as tree structure. It is
best way represented as recursive composition.
73. Class diagram:
Participants:
• Component
– declares the interface for objects in the composition.
– implements default behavior for the interface common to all classes, as appropriate.
– declares an interface for accessing and managing its child components.
– (optional) defines an interface for accessing a component's parent in the recursive
structure, and implements it if that's appropriate.
• Leaf
– represents leaf objects in the composition. A leaf has no children.
– defines behavior for primitive objects in the composition.
74. • Composite
– defines behavior for components having children.
– stores child components.
– implements child-related operations in the Component interface.
• Client
– manipulates objects in the composition through the Component
interface
75. Implementation:
package com.learning.designpattern.CompositePattern;
import java.util.ArrayList;
import java.util.List;
//component
interface Graphic{
void print();
}
// composite
class CompositeGraphic implements Graphic{
private List<Graphic> compGraphics = new ArrayList <Graphic>();
public void print(){
for(Graphic graphic: compGraphics){
graphic.print();
}
}
public void add(Graphic graphic) {
compGraphics.add(graphic);
}
public void remove(Graphic graphic) {
compGraphics.remove(graphic);
}
76. //Leaf
class Circle implements Graphic{
public void print(){
System.out.println("Circle");
}
}
class Elipse implements Graphic{
public void print(){
System.out.println("Elipse");
}
}
class Client{
public static void main(String args[]){
Circle circle1 = new Circle();
Circle circle2 = new Circle();
Circle circle3 = new Circle();
Circle circle4 = new Circle();
Elipse elipse = new Elipse();
CompositeGraphic compGraphic1 = new CompositeGraphic();
CompositeGraphic compGraphic2 = new CompositeGraphic();
CompositeGraphic compGraphic3 = new CompositeGraphic();
78. Advantages:
– Defines class hierarchies consisting of primitive objects and composite
objects.
– Makes the client code simple. Client can treat composite structures and
individual objects uniformly.
– Makes it easier to add new kinds of component
Disadvantage:
The disadvantage of making it easy to add new components is that it makes it
harder to restrict the components of composite
JAVA CORE API Example
java.awt.Container#add(Component) (practically all over Swing thus)
javax.faces.component.UIComponent#getChildren() (practically all over JSF UI
thus)
79. Flyweight
Definition: Use sharing to support large numbers of fine-grained
objects efficiently.
The pattern here states about a mechanism by which you can
avoid creating a large number of object instances to represent
the entire system
• Analogy: The typical example you can see on this in every book will be of folders.
The folder with name of each of the company employee on it, so, the attributes of
class Folder are: ‘Selected’ , ‘Not Selected’ and the third one is ‘employeeName’.
With this methodology, we will have to create 2000 folder class instances for
each of the employees. This can be costly, so we can create just two class
instances with attributes ‘selected’ and ‘not selected’ and set the employee’s name
by a method like:
setNameOnFolder(String name);
This way, the instances of class folder will be shared and you will not have to
create multiple instances for each employee.
Another instance, Every time we creating a new rectangle. There has been a color
that has already been used. We are not going to create a new rectangle object.
We are going to share what has been already created with that similar color. The
extrinsic state is going to be the thing different to these rectangles.
81. Participants:
• Flyweight
– declares an interface through which flyweights can receive and act on extrinsic state.
• ConcreteFlyweight
– implements the Flyweight interface and adds storage for intrinsic state, if any. A
ConcreteFlyweight object must be sharable. Any state it stores must be intrinsic, that
is, it must be independent of the ConcreteFlyweight object's context.
• UnsharedConcreteFlyweight
– not all Flyweight subclasses need to be shared. The Flyweight interface enables
sharing, but it doesn't enforce it. It is common for UnsharedConcreteFlyweight
objects to have ConcreteFlyweight objects as children at some level in the flyweight
object structure.
• FlyweightFactory
– creates and manages flyweight objects.
– ensures that flyweight are shared properly. When a client requests a flyweight, the
FlyweightFactory objects supplies an existing instance or creates one, if none exists.
• Client
– maintains a reference to flyweight(s).
– computes or stores the extrinsic state of flyweight(s).
86. Applicability:
– when the application uses large number of objects.
– Storage costs are high because of the quantity of objects.
– The application doesn't depend on object identity.
Advantages:
– Reduction in the number of objects to handle.
– Reduction in memory and storage devices if the objects are
persisted.
Disadvantages:
- Flyweights may introduce run-time costs associated with
transferring, finding, and/or computing extrinsic state,
especially if it was formerly stored as intrinsic state.
Core Java API Example:
java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character,
Short, Long and BigDecimal)
87. Proxy Pattern
• Definition : provide surrogate or place holder for another object
to control access it.
A proxy object can act as the intermediary between the client
and the target object
• Analogy: we want to attach an image with the email. Now, suppose
this email has to be sent to 1 lakh consumers in a campaign.
Attaching the image and sending along with the email will be a
very heavy operation. What we can do instead is, send the image
as a link to one of the servlet. The place holder of the image will
be sent. Once the email reaches the consumer, the image place
holder will call the servlet and load the image at run time straight
from the server
89. Implementation:
package com.learning.designpattern.ProxyPattern;
interface PotOfTeaInterface {
public void pourTea();
}
class PotOfTea implements PotOfTeaInterface {
public PotOfTea() {
System.out.println("Making a pot of tea");
}
public void pourTea() {
System.out.println("Pouring tea");
}
}
class PotOfTeaProxy implements PotOfTeaInterface {
PotOfTea potOfTea;
public PotOfTeaProxy() {}
public void pourTea() {
potOfTea = new PotOfTea();
potOfTea.pourTea();
}
}
90. class TestProxy {
public static void main(String[] args) {
System.out.println("TestProxy: instantiating PotOfTeaProxy");
PotOfTeaInterface potOfTea = new PotOfTeaProxy();
System.out.println(" ");
System.out.println("TestProxy: pouring tea");
potOfTea.pourTea();
}
}
There are different types of proxies (defined in Gang of Four book):
• Virtual proxies create large expensive objects on demand. Icon viewer demonstrate the
usage of the image proxy, that prevents creation of the image object already in constructor.
It can answer itself on some client’s queries, such a getWidth() or getHeight(), without
loading the image into the memory and it loads the image only if the image is really painted.
• Remote proxy is the local representative of the real subject in a different address space
(e.g. remote object on another host). The client thinks that he talks with the remote object,
but there is the proxy between them. The Proxy translates the client’s queries in remote
calls, gets the results of the query from remote object and forwards them to the client. One
good example of the remote proxies are the stub classes in Java RMI:
Calculator RMI Service.
• Protection proxies grant or deny the client access to the real subject.
• “Smart references” extend the functionality of the “simple” pointers and perform additional
maintenance actions every time the real subject is accessed. They can e.g. count the number
of references to the real subject or test, if the real subject is locked to prevent that other
client simultaneously change it.
91. Applicability:
– counting the number of references to the real object so that it can
be freed automatically when there are no more references
– Loading a persisting object into a memory when it’s first
referenced.
– checking that the real object is locked before it’s accessed to
ensure that no other object can change it.
Advantages:
– A remote proxy can hide the fact that an object resides in a different
address space.
– A virtual proxy can perform optimizations such as creating an object on
demand.
– Both protection proxies and smart references allow additional housekeeping
tasks when an object is accessed
91
92. Disadvantages:
– counting the number of references to the real object so that it can
be freed automatically when there are no more references
– Loading a persisting object into a memory when it’s first
referenced.
– checking that the real object is locked before it’s accessed to
ensure that no other object can change it.
Java core API Example:
– java.lang.reflect.Proxy
– java.rmi.*
– javax.ejb.EJB
– javax.inject.Inject
– javax.persistence.PersistenceContext
92
93. Facade
• The facade pattern (also spelled façade) is a software design
pattern commonly used with object-oriented programming. The
name is by analogy to an architectural façade. A facade is an
object that provides a simplified interface to a larger body of
code, such as a class library.
• A segment of the client community needs a simplified interface
to the overall functionality of a complex subsystem.
Analogy:
Assume penta-house has around 10 doors associated with each
room but the outsider can enter via only one main door. Then main
door can be façade to reach out to all rooms connected via 10
doors.
Assume one of the Shopping mall has portal application for
supplier management, billing management, inventory management
and order management modules. The dashboard of customer
support manager can see all services via single dashboard built
top of all modules connected via Dashboard façade.
93
94. Class diagram:
94
• Facade
– The facade class abstracts Packages 1, 2, and 3 from the rest of the
application.
• Clients
– The objects are using the Facade Pattern to access resources from the
Packages.
95. Implementation:
/* Complex parts */
class CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}
class HardDrive {
public byte[] read(long lba, int size) { ... }
}
class Memory {
public void load(long position, byte[] data) { ... }
}
95
96. Implementation:
/* Facade */
class ComputerFacade {
private CPU processor;
private Memory ram;
private HardDrive hd;
public ComputerFacade() {
this.processor = new CPU();
this.ram = new Memory();
this.hd = new HardDrive();
}
public void start() {
processor.freeze();
ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
processor.jump(BOOT_ADDRESS);
processor.execute();
}
} 96
97. Implementation:
/* Client */
class You {
public static void main(String[] args) {
ComputerFacade computer = new ComputerFacade();
computer.start();
}
}
97
98. Applicability
• A simple interface is required to access a complex system.
• The abstractions and implementations of a subsystem are tightly
coupled.
• Need an entry point to each level of layered software.
• System is very complex or difficult to understand.
Advantages:
• We can use the façade pattern to collate all the complex method
calls and related code blocks and channelizes it through one
single Façade class. In this way with respect to client there is
only one single call. Even if we make changes to the subsystem
packages / class and their logic there is no impact to the client
call. In short this increases loose coupling.
• It makes easier to use and maintain creating a more structured
environment and reduces dependencies between libraries or other
packages.
98
99. Disadvantages:
• One of the drawback is that the subsystem methods are
connected to the Façade layer. If the structure of the
subsystem changes then it will require subsequent change to the
Façade layer and client methods.
JAVA/J2EE Core API Examples
• javax.faces.context.FacesContext, it internally uses among others
the abstract/interface types LifeCycle, ViewHandler,
NavigationHandler and many more without that the enduser has
to worry about it (which are however overrideable by injection).
• javax.faces.context.ExternalContext, which internally uses
ServletContext, HttpSession, HttpServletRequest,
HttpServletResponse, etc.
99
100. Decorator
• Wrapper pattern
• Attach additional responsibilities to an object dynamically.
• Decorators provide a flexible alternative to subclassing for
extending functionality
Analogy:
In a graphical user interface toolkit, let you add properties like
borders or behaviors like scrolling to any user interface
component.
Assume you visit pizza shop, there may be varieties of items
forms combo of pizza which is made on top of base pizza. So
different customization based on customer request can be
considered as decorator on base pizza. In any sequence combo
would be prepared with multiple choices and finally base pizza and
combo choiced price should be total cost for pizza.
100
102. Implementation:
Window.java
package com.designpattern.learning.decoratorpattern;
public interface Window {
public void draw();
public String getDescription();
}
SimpleWindow.java
package com.designpattern.learning.decoratorpattern;
public class SimpleWindow implements Window{
public void draw(){
//System.out.println ("Simple Window");
}
public String getDescription(){
return "Simple Window";
}
}
102
103. WindowDecorator.java
package com.designpattern.learning.decoratorpattern;
public abstract class WindowDecorator implements Window {
protected Window decoratedWindow;
public WindowDecorator (Window decoratedWindow) {
this.decoratedWindow = decoratedWindow;
}
}
HorizontalScrollBarDecorator.java
package com.designpattern.learning.decoratorpattern;
public class HorizontalScrollBarDecorator extends WindowDecorator{
public HorizontalScrollBarDecorator (Window decoratedWindow) {
super(decoratedWindow);
}
public void draw() {
drawHorizontalScrollBar();
decoratedWindow.draw();
}
103
104. private void drawHorizontalScrollBar() {
// draw the horizontal scrollbar
}
public String getDescription() {
return decoratedWindow.getDescription() + ", including horizontal
scrollbars";
}
}
VerticalScrollBarDecorator.java
package com.designpattern.learning.decoratorpattern;
public class VerticalScrollBarDecorator extends WindowDecorator {
public VerticalScrollBarDecorator (Window decoratedWindow) {
super(decoratedWindow);
}
public void draw() {
drawVerticalScrollBar();
decoratedWindow.draw();
}
104
105. private void drawVerticalScrollBar() {
// draw the vertical scrollbar
}
public String getDescription() {
return decoratedWindow.getDescription() + ", including vertical
scrollbars";
}
}
DecoratedWindowTest.java
package com.designpattern.learning.decoratorpattern;
public class DecoratedWindowTest {
public static void main (String[] args) {
Window decoratedWindow = new HorizontalScrollBarDecorator (
new VerticalScrollBarDecorator (new SimpleWindow()));
// print the Window's description
System.out.println (decoratedWindow.getDescription());
}
}
105
106. Applicability
• Add responsibilities to individual objects dynamically and
transparently, that is, without affecting other objects.
• Be able to withdraw responsibilities
For example: The
java.util.Collections.unmodifiableCollection(Collection) removies
the ability to change a given collection by wrapping it with a
decorator that throws an UnSupportedException when you try to
modify the Collection.
• When extension by subclassing is impractical, such as when a
large number of independent extensions produce an explosion of
subclasses to support every combination. Or a class is unavailable
for subclassing.
Advantages:
• It provides a more flexible way to add responsibilities to objects
than can be had with static (multiple) inheritance.
• Decorators offers a pay-as-you-go approach to adding
responsibilities 106
107. Disadvantages:
• A design that uses decorator often results in systems composed
of lots of little objects that all look alike
• Decorators can result in many small objects in our design, and
overuse can be complex
• Decorators can cause issues if the client relies heavily on the
components concrete type
JAVA/J2EE Core API Examples
• All subclasses of java.io.InputStream, OutputStream, Reader and
Writer have a constructor taking an instance of same type.
• java.util.Collections, the checkedXXX(), synchronizedXXX() and
unmodifiableXXX() methods.
• javax.servlet.http.HttpServletRequestWrapper and
HttpServletResponseWrapper
107
109. Observer pattern
Definition: "Define a one-to-many dependency between objects so
that when one object changes state, all its dependents are
notified and updated automatically.“
The Observer pattern allows an object (an Observer) to watch
another object (a Subject). The subject and observer to have a
publish/subscribe relationship. Observers can register to receive
events from the Subject. When the subject can update the
Observers when certain expected events occur.
The Observer pattern helps create a family of cooperating
classes, while maintaining consistency and avoiding tight-coupling
Analogy:
In a company, any change in HR Department publish policy that
should be notified to all their employees. It means HR
Department is a subject and all other employees are observer.
109
110. analogy
• The Observer defines a one-to-many relationship so that when
one object changes state, the others are notified and updated
automatically. 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 110
111. Class diagram
111
Participants:
Subject: Maintains list of Observer references. Subject also
provides an interface for attaching and detaching Observer
Objects.
Observer: Defines an updating interface for objects that should
be notified of changes in a subject.
Concrete Subject: Stores state of interest to ConcreteObserver
objects and sends notifications to its observers upon state
changes.
ConcreteObserver: Maintains a reference to a ConcreteSubject
object and a state that should stay consistent with the subject's
113. class CeilObserver extends Subscriber{
public CeilObserver(Publisher sub){
this.sub =sub;
}
public void update(){
System.out.println("Ceil Of Number : t"+Math.ceil(sub.getState()));
}
}
class FloorObserver extends Subscriber{
public FloorObserver(Publisher sub){
this.sub =sub;
}
public void update(){
System.out.println("Floor Of Number : t"+Math.floor(sub.getState()));
}
}
class SqrtObserver extends Subscriber{
public SqrtObserver(Publisher sub){
this.sub =sub;
}
public void update(){
System.out.println("Sqrt Of Number : t"+Math.sqrt(sub.getState()));
} } 113
114. class Publisher{
private double state=0;
private List<Subscriber> observers = new ArrayList<Subscriber> ();
public void addObserver(Subscriber observer){
observers.add(observer);
}
public void removeObserver(Subscriber observer){
observers.remove(observer);
}
public double getState(){
return state;
}
public void setState(double state){
this.state = state;
notifyObservers();
}
private void notifyObservers(){
for(Subscriber obs: observers){
obs.update();
}
}
}
114
115. public class ObserverDemo{
public static void main(String args[]){
Publisher sub = new Publisher();
sub.addObserver(new CeilObserver(sub));
sub.addObserver(new FloorObserver(sub));
sub.addObserver(new SqrtObserver(sub));
sub.setState(8.6);
}
}
Output:
– Ceil Of Number : 9.0
– Floor Of Number : 8.0
– Sqrt Of Number : 2.932575659723036
115
116. Applicability:
– When the abstraction has two aspects with one dependent
on the other. Encapsulating these aspects in separate
objects will increase the chance to reuse them independently.
– When the subject object doesn't know exactly how many
observer objects it has.
– When the subject object should be able to notify it's
observer objects without knowing who these objects are.
Advantages:
– Minimal coupling between subject and observer
– Support for event broad casting
Disadvantages:
– Simple update interface should be used
– Possible cascading of notification
116
117. Java core API Example:
– java.util.Observer/java.util.Observable (rarely used in real
world though)
– All implementations of java.util.EventListener (practically all
over Swing thus)
– javax.servlet.http.HttpSessionBindingListener
– javax.servlet.http.HttpSessionAttributeListener
– javax.faces.event.PhaseListener
117
118. Chain of Responsibility:
Definition: Avoid coupling the sender of a request to its receiver by
giving more than one object a chance to handle the request. Chain
the receiving objects and pass the request along the chain until
an object handles it.
Analogy:
Catching Exception by in java is good example for Chain of
Responsibility.
118
120. class ConcreteHandler1 extends Handler {
public void handleRequest() {
System.out.println("handler1");
if(getSuccessor()!=null)
getSuccessor().handleRequest();
}
}
class ConcreteHandler2 extends Handler {
public void handleRequest() {
System.out.println("handler2");
if(getSuccessor()!=null)
getSuccessor().handleRequest();
}
}
class ConcreteHandler3 extends Handler {
public void handleRequest() {
System.out.println("handler3");
if(getSuccessor()!=null)
getSuccessor().handleRequest();
}
}
120
121. class ConcreteHandler4 extends Handler {
public void handleRequest() {
System.out.println("handler4");
if(getSuccessor()!=null)
getSuccessor().handleRequest();
}
}
public class CORClient {
public static void main(String args[]){
try{
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handler3 = new ConcreteHandler3();
Handler handler4 = new ConcreteHandler4();
handler1.setSuccessor( handler2 );
handler2.setSuccessor( handler3 );
handler3.setSuccessor( handler4 );
handler1.handleRequest();
}catch( Exception e ){
e.printStackTrace();
} }
}
121
122. Applicability:
• When more than one object may handle request but we don’t
know exact object
• Handle or forward model
Advantages:
• Decouples the sender of the request and its receivers.
• Simplifies your object as it doesn’t have to know about the chain
structure and keep direct references to its members.
• Allows you to add or remove responsibilities dynamically by
changing the members or order of the chain.
Disadvantages:
• Hard to observe the run-time characteristics and debug.The
order of Observer notifications is undependable
Java Core API Example:
122
123. Iterator
Definition:"Provide a way to access the elements of an aggregate
object sequentially without exposing its underlying
representation.“
The Iterator pattern is one, which allows you to navigate through
a collection of data using a common interface without knowing
about the underlying implementation.
Analogy: In our life Daily routine having breakfast, lunch and dinner
would be repeated till the end of our life can be iterator pattern.
Life may be collection and daily routine would be iteration.
123
127. else{
throw new IndexOutOfBoundsException();
}
return object;
}
public Object next()
throws IndexOutOfBoundsException{
Object object = null;
if( index + 1 < aggregate.storage.size() ){
index += 1;
object = aggregate.storage.elementAt(index);
}
else{
throw new IndexOutOfBoundsException();
}
return object;
}
127
128. public boolean isDone(){
boolean result = false;
if( aggregate.storage.isEmpty() ||
index == aggregate.storage.size()-1 ){
result = true;
}
return result;
}
public Object currentItem()
throws IndexOutOfBoundsException{
Object object = null;
if( index < aggregate.storage.size() ){
object = aggregate.storage.elementAt( index );
}
else{
throw new IndexOutOfBoundsException();
}
return object;
}
}
128
129. package com.designpattern.learning.iteratorpattern;
import java.util.Vector;
public class Client {
public static void main( String arg[] )
{
try{
Aggregate aggregate = new ConcreteAggregate();
Iterator iterator = aggregate.createIterator();
System.out.println("Traverse ConcreteAggregate Using Iterator");
iterator.first();
while(!iterator.isDone()){
Object item = iterator.currentItem();
System.out.println("item::"+item.toString());
iterator.next();
}
}catch( Exception e ){
e.printStackTrace();
}
}
}
129
130. Applicability:
– To access an aggregate object’s contents without exposing its internal
representation.
– To support multiple traversal of aggregate objects.
– To provide a uniform interface for traversing different aggregate structures
(that is , to support polymorphic iteration)
Advantages:
– It supports variations in the traversal of an aggregate. complex aggregates
may be traversed in many ways.
– Iterator’s traversal interface obviates the need for a similar interface in
aggregate, thereby simplifying the aggregate’s interface.
– more than one traversal can be pending on an aggregate.
Disadvantage:
– Internal collection is exposed to outside world or external object
Java core API Example:
– All implementations of java.util.Iterator (thus among others also
java.util.Scanner!).
– All implementations of java.util.Enumeration
130
131. Mediator
Definition: “Define an object that encapsulates how a set of objects
interact. Mediator promotes loose coupling by keeping objects
from referring to each other explicitly, and it lets you vary their
interaction independently.”
Analogy: The stock exchange like BSE /NSE can act as mediator for
traders in between sellers and buyers.
131
132. Class diagram:
Participants:
• Mediator - defines the interface for communication between Colleague
objects
• ConcreteMediator - implements the Mediator interface and coordinates
communication between Colleague objects. It is aware of all the
Colleagues and their purpose with regards to inter communication.
• ConcreteColleague - communicates with other Colleagues through its
Mediator
132
133. Implementation:
class Sell{
private float price;
private float qty;
public void doTransaction(float qty){
System.out.println("SELLING:");
this.setPrice(qty * 10.5f);
}
public float getPrice(){
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
133
134. class Buy{
private float price;
private float qty;
public void doTransaction(float qty){
System.out.println("Buying:");
this.setPrice(qty * 10.5f);
}
public float getPrice(){
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
interface Mediator{
public void doTransaction(String type,float qty);
}
134
135. class ConcreteMediator implements Mediator{
float price;
Sell s = new Sell();
Buy b = new Buy();
public void doTransaction(String type,float qty){
if(type=="SELL"){
s.doTransaction(qty);
this.price = s.getPrice();
}else{
b.doTransaction(qty);
this.price = b.getPrice();
}
System.out.println("Price::"+price);
}
}
135
136. package com.designpattern.learning.mediatorpattern;
public class Client {
public static void main(String args[]){
Mediator m = new ConcreteMediator();
System.out.println("Customer:-->Selling");
m.doTransaction("SELL", 100);
System.out.println("Customer:-->Buying");
m.doTransaction("BUY", 10);
}
}
136
137. Applicability:
– A set of objects communicates well-defined but complex ways.
– Reusing objects is difficult because it refers to and communicates
with many other objects.
– A behavior that’s distributed between several classes should be
customizable without a lot of sub classing
Advantages:
– A mediator localizes behavior that otherwise would be distributed
among several objects.
– A mediator promotes loose coupling between colleagues.
– It replaces many-to-many interactions with one-to-many interactions
between the mediator and its colleagues
137
138. Disadvantages:
The mediator pattern trades complexity of interaction for
complexity in the mediator.
JAVA CORE LIBRARIES EXAMPLE:
java.util.Timer (all scheduleXXX() methods)
java.util.concurrent.Executor#execute()
java.util.concurrent.ExecutorService (the invokeXXX() and submit()
methods)
java.util.concurrent.ScheduledExecutorService (all scheduleXXX()
methods)
java.lang.reflect.Method#invoke()
138
139. Strategy:
• Definition : "Define a family of algorithms, encapsulate each one,
and make them interchangeable. Strategy lets the algorithm vary
independently from clients that use it.“
• An object controls which of a family of methods is called. Each
method is in its' own class that extends a common base class.
Analogy: In cricket, Each team will be having second batting to win
the match. So each team should have chasing strategy. It may
vary from team to team. So chase method may be executed in
different approach or strategy to successful chase to win the
match. So all possible strategies adopted to win the match would
be best example for strategy pattern.
139
142. class AlgorithmB implements IStratergy{
public void execute(){
System.out.println("Algorithm:B");
}
}
class Context{
IStratergy stratergy;
Context(IStratergy stratergy){
this.stratergy = stratergy;
}
public void execute(){
stratergy.execute();
}
}
public class Client {
public static void main(String args[]){
Context context;
context = new Context(new AlgorithmA());
context.execute();
context = new Context(new AlgorithmB());
context.execute();
}
} 142
143. Applicability:
– 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.
– A class defines many behaviors , and these appear as multiple
conditional statements in its operations.
Advantages:
– It offers an alternative to conditional statements for
selecting desired behavior.
– Hierarchy of strategy classes define a family of algorithms or
behaviors for contexts to reuse.
– It can provide different implementations of the same
behavior.
143
144. Disadvantages:
– Client must be aware of different strategy.
– Increased number of objects
Java Core libraries example
– java.util.Comparator#compare(), executed by among others
Collections#sort().
– javax.servlet.http.HttpServlet, the service() and all doXXX()
methods take HttpServletRequest and HttpServletResponse
and the implementor has to process them (and not to get hold
of them as instance variables!).
– javax.servlet.Filter#doFilter()
144
145. Template Method:
Definition: "Define the skeleton of an algorithm in an operation,
deferring some steps to subclasses. Template Method lets
subclasses redefine certain steps of an algorithm without
changing the algorithms structure.“
The template method defines a skeleton of an algorithm in an
operation and defers some steps to subclasses. Home Builders
use the template method when developing a new subdivision. A
typical subdivision consists of a limited number of floor plans
with diff variations available for each. Within a floor plan, the
foundation, framing, plumbing, and wiring will be identical for
each house. Variation is introduced in the later stages of
construction to produce a wider variety of models
Analogy:
In college Exam, should have steps prepare question paper,
define marks , duration , conduct exam and evaluation would be
template method to be followed irrespective of degrees and
repeated for each course.
145
146. IMPLEMENTATION:
abstract class Game{
abstract public void initialize();
abstract public void startGame();
abstract public void playGame();
abstract public void stopGame();
/* Template Method */
public void play(){
initialize();
startGame();
playGame();
stopGame();
}
}
146
147. class Chess extends Game{
public void initialize(){
System.out.println("Chess:Arranged");
}
public void startGame(){
System.out.println("Chess:Started");
}
public void playGame(){
System.out.println("Chess:Playing...");
}
public void stopGame(){
System.out.println("Chess:win");
}
}
class Cricket extends Game{
public void initialize(){
System.out.println("Cricket:Arranged");
}
public void startGame(){
System.out.println("Cricket:Started");
}
147
148. public void playGame(){
System.out.println("Cricket:Playing...");
}
public void stopGame(){
System.out.println("Cricket:win");
}
}
package com.designpattern.learning.templatePattern;
public class Client {
public static void main(String args[]){
Game game = new Chess();
game.play();
game = new Cricket();
game.play();
}
}
148
149. Applicability:
– To implement the invariant parts of an algorithm once and leave it up to
subclasses to implement the behavior that can vary.
– To control the subclass extensions.
– When common behavior among subclasses should be factored and localized in a
common class to avoid code duplication.
Advantages:
– Template methods are a fundamental technique for code reuse. They
particularly important in class libraries.
– It’ s easy to forget to call the inherited operation. We can transform such an
operation into a template method to give the parent control how subclasses
extend it.
149
150. Disadvantages:
– Debugging sometimes confusing.
– Any change in interface or implementation disturb whole chain.
Java core libraries example:
– All non-abstract methods of java.io.InputStream, java.io.OutputStream,
java.io.Reader and java.io.Writer.
– All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and
java.util.AbstractMap.
– javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a
HTTP 405 "Method Not Allowed" error to the response. You're free to
implement none or any of them.
150
151. State Pattern:
• Definition: "Allow an object to alter its behavior when its internal
state changes. The object will appear to change its class."
• Analogy: Assume a person X, if somebody asked money to him, X
will decide for giving money based on his vitamin_M
variable(state of Money), this type of scenario can be assume to
be state pattern.
In-otherwords, based on state of object, entire behavior
changed. In these type of scenario state pattern holds good.
• Another instance would be Politician object may change it’s
behavior based on their current status like before election give
respect to people, after win they expect respect from all people
and after minister expect people to listen always his rules and
regulation. It means politician object behaves differently in
different situation. This scenario follows state pattern.
151
152. Class diagram:
Participants:
Context: Acts as the interface to clients. The Context object maintains an instance
of a ConcreteState subclass that represents the current state. The context
delegates the requests to the concrete state object that represents the current
state. Typically, the context passes itself as an argument to the current state
object, which changes the current state of the context.
State: An interface for encapsulating the behavior associated with a particular state
of the Context.
Concrete State subclasses: Define the behavior associated each state.
152
153. Implementation :
interface Permission{
public String handlePermission();
}
class GrantPermission implements Permission{
public String handlePermission() {
return "Grant Permission";
}
}
class RevokePermission implements Permission{
public String handlePermission(){
return "Revoke Permission";
}
}
class AcceptPermission implements Permission{
public String handlePermission(){
return "Accept Permission";
}
} 153
154. class PersonContext{
private Permission permission;
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
public String request(){
return permission.handlePermission();
}
}
package com.designpattern.learning.statepattern;
public class StatePatternDemo {
public static void main(String[] args) {
Permission state = new AcceptPermission();
PersonContext context = new PersonContext();
context.setPermission( state );
System.out.println(context.request());
154
155. state = new GrantPermission();
context.setPermission( state );
System.out.println( context.request());
state = new RevokePermission();
context.setPermission( state );
System.out.println( context.request());
}
}
155
156. Applicability:
• An object’s behavior depends on its state, and it must change its
behavior at run-time depending on that state.
• Operations have large, multipart conditional statements that
depend on the object’s state.
Advantages:
• It localizes state-specific behavior and partitions behavior for
different states.
• It makes state transitions explicit.
• The state they represent is encoded entirely in their type-then
contexts can share a state object
156
157. Disadvantages:
• States and transitions are more hard-coded and more code
changes are needed to extend.
JAVA CORE LIBRARIES EXAMPLE:
• javax.faces.lifecycle.LifeCycle#execute() (controlled by
FacesServlet, the behaviour is dependent on current phase
(state) of JSF lifecycle)
157
158. Memento:
• Definition: “Without violating encapsulation, capture and
externalize an object’s internal state so that the object can be
restored to this state later.”
• Analogy: There can be infinite number of setting for each piece
of audio mixing. To remember this, engineer can take photograph
of this and may be used later if required.
participant code:
mixing equipment Original object whose state being changed
photograph ->memento
The engineer -> that takes the photo originators.
The drawer->where the memento is stored and the caretaker.
158
159. Analogy II :
Most people are particular about the radio station that they listen
to in the car. When there is more than one driver(Father,
Mother, child), the radio station likely to have Changed with the
driver. the preset buttons serve as mementos, allowing the radio
to be restored to the desired tunning with one button push.
Participants:
radio tunning-->original object, whose state to be saved
preset button-->is the memento
the driver-->who sets the preset button is the originator. he will
also use the memento to restore the state of the radio tunning.
the radio--> where the button is located is the care taker.
159
161. Implementation:
• //originator
class RadioTune{
private String tune;
public void setPresetButton( PresetButton presetButton ){
tune = presetButton.getTune();
}
public PresetButton createPresetButton(){
System.out.println("Originator: Saving to Memento."+tune);
return new PresetButton( tune );
}
}
//memento
class PresetButton{
private String tune;
public PresetButton(String tune ){
this.tune = tune;
}
161
162. public String getTune(){
return tune;
}
public void setTune( String tune ){
this.tune = tune;
}
}
//care taker
class Radio {
private List<Object> savedTunes = new ArrayList<Object>();
public void addPresetButton(Object m) {
savedTunes.add(m);
}
public Object getPresetButton(int index) {
System.out.println("size::"+savedTunes.size());
return savedTunes.get(index);
}
}
162
163. package com.designpattern.learning.mementopattern;
import java.util.ArrayList;
import java.util.List;
public class MementoDemo {
public static void main(String args[]){
Radio radio = new Radio();
RadioTune radioTune = new RadioTune();
radioTune.setPresetButton(new PresetButton("Kannada Song"));
radioTune.setPresetButton(new PresetButton("English Song"));
radio.addPresetButton( radioTune.createPresetButton());
radioTune.setPresetButton(new PresetButton("Hindi Song"));
radio.addPresetButton( radioTune.createPresetButton());
radioTune.setPresetButton(new PresetButton("Telagu Song"));
radio.addPresetButton( radioTune.createPresetButton());
//restore
Object p= radio.getPresetButton(2);
if(p instanceof PresetButton){
PresetButton memento = (PresetButton)p;
String state = memento.getTune();
System.out.println("Originator: State after restoring from Memento: "+state);
}
} } 163
164. Applicability:
– A snapshot of (some part of ) an object’s state must be saved so
that it can be restored to that state later , and
– A direct interface to obtaining the state would expose
implementation details and break the object’s encapsulation.
Advantages:
– It shields other objects from potentially complex originator
internals, thereby preserving encapsulation boundaries.
– It simplifies originator
Disadvantages:
It may be difficult in some languages to ensure that only the originator
can access the memento’s state
Java core libraries example
java.util.Date (the setter methods do that, Date is internally represented by a
long value)
All implementations of java.io.Serializable
All implementations of javax.faces.component.StateHolder
164
165. Interpreter
• Definition: "Given a language, define a representation for its
grammar along with an interpreter that uses the representation
to interpret sentences in the language."
• Analogy:
165
Musical notation provides a
grammatical representation for
the pitch and duration of sounds.
when musicians play from score,
they are interpreters, interpreting
that grammar.
participants:
Musical Notation -->abstract
expression
Notes --> terminal expression
Time & key Signature-->Non-
terminal expression
context or information-->global to
interpreter
musician -->interpreter
166. Class diagram:
• Implementation:
interface Expression {
public void interpret(Stack<Integer> s);
}
class TerminalExpression_Number implements Expression {
private int number;
public TerminalExpression_Number(int number) { this.number = number; }
public void interpret(Stack<Integer> s) { s.push(number); }
}
166
167. class TerminalExpression_Plus implements Expression {
public void interpret(Stack<Integer> s) { s.push( s.pop() + s.pop() ); }
}
class TerminalExpression_Minus implements Expression {
public void interpret(Stack<Integer> s) {
s.push( - s.pop() + s.pop() ); }
}
class Parser {
private ArrayList<Expression> parseTree = new ArrayList<Expression>(); // only one NonTerminal
Expression here
public Parser(String s) {
for (String token : s.split(" ")) {
System.out.println("token::"+token);
if (token.equals("+")) parseTree.add( new TerminalExpression_Plus() );
else if (token.equals("-")) parseTree.add( new TerminalExpression_Minus() );
// ...
else parseTree.add( new TerminalExpression_Number(Integer.valueOf(token)) );
}
}
167
168. public int evaluate() {
Stack<Integer> context = new Stack<Integer>();
for (Expression e : parseTree) e.interpret(context);
return context.pop();
}
}
package com.designpattern.learning.interpreterpattern;
import java.util.ArrayList;
import java.util.Stack;
public class Client {
public static void main(String[] args) {
String expression = "42 4 2 - +";
Parser p = new Parser(expression);
System.out.println("'" + expression +"' equals " + p.evaluate());
}
}
168
169. Applicability:
– There is a language to interpret, and you can represent statements in the language as
abstract syntax tree.
– Efficiency is not a critical concern.
Advantages:
– It’s easy to change and extend the grammar.
– Implementation of grammar is easy too.
– It ‘s easier to evaluate an expression in a new way.
Disadvantages:
-For complex grammars, the class hierarchy for the grammar becomes large and
unmanageable
Java Core libraries example
– java.util.Pattern
– java.text.Normalizer
– All subclasses of java.text.Format
– All subclasses of javax.el.ELResolver
169
170. Command pattern
Definition: Encapsulate a request as an object, thereby letting you
parameterize clients with different requests, queue or log requests and
supports for undoable operations.
This is data-driven pattern. The client invokes a particular module using
a command. The client passes a request, this request gets propagated as
a command. The command request maps to particular modules. According
to the command, a module is invoked
Analogy:
A classic example of this is a restaurant. A customer goes to restaurant
and orders the food according to his/her choice. The waiter/ waitress
takes the order (command, in this case) and hands it to the cook in the
kitchen. The cook can make several types of food and so, he/she
prepares the ordered item and hands it over to the waiter/waitress who
in turn serves to the customer.
170
172. Implementation
Command.java
package com.designpattern.learning.command;
public interface Command {
public void execute();
}
commandA.java
package com.designpattern.learning.command;
public class CommandA implements Command {
public void execute(){
System.out.println ( "Inside Command A");
}
}
commandB.java
package com.designpattern.learning.command;
public class CommandB implements Command {
public void execute(){
System.out.println ( "Inside Command B");
}
}
172
173. Invoker.java
package com.designpattern.learning.command;
public class Invoker {
public void doCommand (Command cmd){
cmd.execute();
}
}
Client.java
package com.designpattern.learning.command;
public class Client {
public static void main (String args []){
Invoker invoke = new Invoker();
System.out.println ("Command A Encapsulated");
CommandA cmdA = new CommandA();
invoke.doCommand (cmdA);
System.out.println ("Command B Encapsulated");
CommandB cmdB = new CommandB();
invoke.doCommand(cmdB);
}
}
173
174. Applicability
• Parameterize objects by an action to perform.
• Specify, queue , and execute requests at different times.
• The command’s execute operation can store state for reversing its
effects in the command itself.
• Support logging changes so that they can be reapplied in case of a
system crash.
• Structure a system around high-level operations built on primitives
operations.
Advantages:
• Reduces complexity of decision logic
• Provides easy extensibility
• Can place multiple commands on a queue for asynchronous
processing
174
175. • Can execute commands in separate threads or on remote
computers
• The client do not know who the recipient is.
Disadvantages:
• Might create significant overhead in object creation, destruction
and use.
Core java libraries example:
• All implementations of java.lang.Runnable
• All implementations of javax.swing.Action
175
176. Visitor Pattern
Represent an operation to be performed on the elements of an
object structure. Visitor lets you define a new operation without
changing the classes of the elements on which it operates
Inotherwords, the visitor design pattern is a way of separating an
algorithm from an object structure. A practical result of this
separation is the ability to add new operations to existing object
structures without modifying those structures.
Analogy: Local trip in a local supermarket to purchase some items,
walking in store by picking up various items required and putting
into cart such as a bunch of bananas, Greeting card for some
ceremony, rice and froti drink and chocolates.
At the end, you may reach cash counter, there cashier reads each
items from cart and start counting as well as reading cost. finally
he gives a bill for total purchased.This resembles visitor pattern.
176
179. Implementation
CarElement.java
package com.designpattern.learning.visitorpattern.example2;
public interface CarElement {
public void accept (Visitor visitor);
}
Body.java
package com.designpattern.learning.visitorpattern.example2;
public class Body implements CarElement {
private int bodyCost;
private String specification;
Body(int bodyCost,String specification){
this.bodyCost = bodyCost;
this.specification = specification;
}
public String getSpceification () {
return specification;
}
179
180. public int getCost() {
return bodyCost;
}
public void accept (Visitor visitor){
visitor.visit (this);
}
}
Wheel.java
package com.designpattern.learning.visitorpattern.example2;
public class Wheel implements CarElement{
private String name;
private int wheelCost;
private String specification;
Wheel (String name, int wheelCost, String specification){
this.name = name;
this.wheelCost = wheelCost;
this.specification = specification;
}
180
181. String getName (){
return name;
}
public int getCost(){
return wheelCost;
}
public String getSpceification(){
return specification;
}
public void accept (Visitor visitor){
visitor.visit (this);
}
}
Engine.java
package com.designpattern.learning.visitorpattern.example2;
public class Engine implements CarElement {
private int engineCost;
private String specification;
Engine (int engineCost, String specification){
this.engineCost = engineCost;
this.specification = specification;
}
181
182. public int getCost() {
return engineCost;
}
public String getSpceification() {
return specification;
}
public void accept (Visitor visitor){
visitor.visit (this);
}
}
Car.java
package com.designpattern.learning.visitorpattern.example2;
public class Car {
CarElement[] elements;
public Car() {
this.elements = new CarElement[]
{ new Wheel ("front left",2000,"MRF"), new Wheel ("front right",2000,"MRF"),
new Wheel ("back left",2000,"MRF") , new Wheel ("back right",2000,"MRF"),
new Body(100,"ASHOK LEYLAND"), new Engine(10000,"TATA") };
}
182
184. 184
public void visit (Engine engine) {
totalCost+ = engine.getCost();
System.out.println ("total cost of engine");
}
public void visit( Body body) {
totalCost+= body.getCost();
}
public void visit (Car car) {
for(CarElement element : car.getElements()) {
element.accept (this);
}
System.out.println ("Total cost of car"+ totalCost);
}
}
185. Applicability
• Add information to legacy libraries without changing legacy code.
• Computation on target objects without modifying their structure
Advantages:
• Allows you to add operations to a Composite structure without
changing the structure itself
• Adding new operations is relatively easy
• The code for operations performed by the Visitor is centralized
185
186. Disadvantages:
• The Composite classes' encapsulation is broken when the Visitor
is used.
• Because the traversal function is involved, changes to the
Composite structure are more difficult
Core java libraries example:
• javax.lang.model.element.AnnotationValue and
AnnotationValueVisitor
• javax.lang.model.element.Element and ElementVisitor
• javax.lang.model.type.TypeMirror and TypeVisitor
• java.nio.file.FileVisitor and SimpleFileVisitor
• javax.faces.component.visit.VisitContext and VisitCallback
186