SlideShare a Scribd company logo
June 25, 2017 www.snipe.co.in 1
Prepared :Mallikarjuna G D
Email: gdmallikarjuna@gmail.com
Design Pattern
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
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
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
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
Java & J2EE patterns
1. Fundamental Design Patterns
Delegation, Interface, Abstract Superclass, Interface and Abstract class,
Immutable, Marker Interface, proxy
2. GRASP(General Responsibility Assignment Software Pattern)
Low coupling&High cohesion,Expert, Creator, Polymorphism, pure fabrication, law
of delemeter, controller.
3. Creational Pattern
Factory Method,Abstract Factory, Builder, Prototype, singleton, object pool
4. Partiioning patterns(Divide and Conquer patterns)
Filter,Composite, Read-only Interface.
5. Structural Patterns
Adapter, Iterator, Bridge, Facade, Fly weight, Decorator, Virtual Proxy, Dynamic
Linkage, Cache Management
6. Behavioral Patterns
Chain of Responsibility, command, Mediator, Observer, strategy, Template
method,
visitor, interpreter, memento, state, Null object.
7
7. concurrency patterns
Single Thread Execution, Lock object, Guarded Suspension, Balking , scheduler,
Read/write Lock, Producer-consumer, Two-phase termination, Double buffering,
Asynchronous processing, Future, session object, lock file, static locking
order, optimistic concurrency, thread pool, ephermal cache item,Transmission
stack
state
8. GUI Design pattern
window per task, Interaction style, Explorable interface, conversational text,
Selection, Form, Direct Manipulation, Limited Selection size, Ephermal feedback,
Disabled Irrelevant things, supplementary window, step-by-step Instructor
9. Organizational Coding patterns
Accessor Method Name, Anonymous Adapter, Symbolic Constant Name
Define Constants in Interfaces,Switch,Extend Super,Intention Revealing method
Conditional Compilation, Composed Method, Checked versus Unchecked Exceptions
Convert Exceptions, Server Socket,Client Socket
10. Code Optimization patterns
Hashed Adapter Objects, Lazy Initialization, Double checked Locking, Loop
unrolling, Lookup Table
12.Testing Patterns
Black Box Testing, White Box Testing,Unit Testing, Integration Testing, System
Testing, Regression Testing, Acceptance Testing, Clean Room Testing
8
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
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
GOF Design Pattern
11
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
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
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
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
• 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
Creational Pattern
17
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
Class diagram:
19
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
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
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
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
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
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
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
Class diagram:
+Connection()
+description() : String
Connection
+OracleConnection()
+description() : String
OracleConnection
+SQLServerConnection()
+description() : String
SQLServerConnection
+MySQLServerConnection()
+description() : String
MySQLServerConnection
+FactoryPattern()
+CreateConnection()
#type : String
FactoryPattern
+callFactoryMethod()
TestFactoryPattern
27
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
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
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
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
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
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.
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
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();
}
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;
}
}
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;
}
}
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.
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
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
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
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
Implementation:
package com.learning.designpattern.PrototypePattern;
import java.util.Hashtable;
abstract class Product implements Cloneable {
private String productCode;
private String description;
public Object clone(){
Object clone = null;
try{
clone = super.clone();
}catch(Exception e){
e.printStackTrace();
}
return clone;
}
public String getProductCode() {
return productCode;
}
public void setProductCode (String productCode) {
this.productCode = productCode;
}
public String getDescription() {
return description;
}
public void setDescription (String description) {
this.description = description;
}
}
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;
}
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
public class Application{
public static void main(String args[]){
ProductCache.loadCache();
Book clonedBook = (Book) ProductCache.getProduct("Prod1");
System.out.println("Product Code = " + clonedBook.getProductCode());
System.out.println("Description = " + clonedBook.getDescription());
System.out.println("Pages" + clonedBook.getNumberOfPages());
DVD clonedDVD = (DVD) ProductCache.getProduct("Prod2");
System.out.println("Product Code = " + clonedDVD.getProductCode());
System.out.println("Description = " + clonedDVD.getDescription());
System.out.println("Duration = " + clonedDVD.getDuration());
}
}
46
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
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
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
Class diagram:
Participants:
– defines an Instance operation that lets clients access its unique instance.
– responsible for creating and maintaining its own unique instance
50
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
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
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()
Structural Pattern
54
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
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
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
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
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
--
package com.designpattern.learning.adapterpattern;
public class AdapterObject implements SecondObjectInterface{
private FirstObject firstObject;
private String firstName;
private String lastName;
AdapterObject(FirstObject firstObject){
this.firstObject = firstObject;
firstName = firstObject.getName().split (" ")[0];
lastName = firstObject.getName().split (" ")[1];
}
59
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
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
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
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.
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
Implementation:
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");
}
}
• 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();
}
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();
}
}
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();
}
}
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
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
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.
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.
• 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
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);
}
//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();
compGraphic1.add(circle1);
compGraphic2.add(circle2);
compGraphic3.add(circle3);
compGraphic1.add(compGraphic2);
compGraphic1.add(compGraphic2);
compGraphic1.add(elipse);
//print
compGraphic1.print();
compGraphic2.print();
compGraphic3.print();
circle4.print();
}
}
Applicability:
– When you want to represent the whole hierarchy or a part of the
hierarchy of objects.
– When you want clients to be able to ignore the differences between
compositions of objects and individual objects.
– When the structure can have any level of complexity and is dynamic.
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)
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.
Class Diagram
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).
Implementation:
package com.learning.designpattern.FlyweightPattern;
import java.util.Hashtable;
class StudentFlyweight{
float avg;
StudentFlyweight(float avg){
this.avg = avg;
}
}
class Student extends StudentFlyweight{
private String name;
private float score;
private float standing = 0.0f;
Student(float avg){
super(avg);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getScore () {
return score;
}
public void setScore (float score) {
this.score = score;
}
public float getStanding() {
return score /(avg-1.0f)*100.0f;
}
}
class FlyweightFactory{
private Hashtable flyweights = new Hashtable();
public Student getFlyweight( Object key, float avg ){
Student flyweight = (Student) flyweights.get (key);
if( flyweight == null ){
flyweight = new Student(avg);
flyweights.put( key, flyweight);
}
return flyweight;
}
}
public class TestFlyweight {
public static void main(String args[]){
String name[] ={"Swamy", "Mohan", "Ram"};
float score[] = {44.5f,22.3f,67.0f};
float total =0.0f;
for(int loop=0;loop<score.length; loop++){
total = total + score[loop];
}
float avg = total/score.length;
FlyweightFactory factory = new FlyweightFactory();
Student student = factory.getFlyweight ("Mallik",avg);
System.out.println("STUDENT INFO");
for(int numStundent = 0; numStundent< name.length; numStundent++){
student.setName (name[numStundent]);
student.setScore (score[numStundent]);
System.out.println (student.getName()+" "+student.getScore()+ " "+student.getStanding());
}
}
}
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)
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
Class diagram:
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();
}
}
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.
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
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
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
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.
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
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
Implementation:
/* Client */
class You {
public static void main(String[] args) {
ComputerFacade computer = new ComputerFacade();
computer.start();
}
}
97
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
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
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
Class diagram:
+operation()
Component
+operation()
ConcreteComponent
+operation()
Decorator
1
*
+operation()
ConcreteDecoratorA
+operation()
+AddedBehavior()
ConcreteDecoratorB
101
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
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
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
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
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
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
Behavioural Pattern
108
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
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
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
implementation
package com.designpattern.learning.observerpattern;
import java.util.ArrayList;
import java.util.List;
abstract class Subscriber{
public Publisher sub;
public abstract void update();
}
112
Client
+addObserver() : Subscriber
+removeObserver() : Subscriber
+getState() : double
+setState() : void
-state : double
+observers : Subscriber
Publisher
+update() : void
Subscriber
-update() : void
CeilSubscriber
-update() : void
FloorSubscriber
-update() : void
SqrtSubscriber
1 *
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
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
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
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
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
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
Class diagram:
package com.designpattern.learning.chainOfResponsibility;
class Handler {
private Handler successor;
public void setSuccessor( Handler successor ){
this.successor = successor;
}
public Handler getSuccessor(){
return successor;
}
public void handleRequest(){
successor.handleRequest();
}
}
119
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
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
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
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
Class diagram:
124
Implementation:
interface Aggregate {
Iterator createIterator();
}
class ConcreteAggregate implements Aggregate {
public Vector storage = new Vector();
public Iterator createIterator(){
storage.add("1");
storage.add("2");
storage.add("3");
storage.add("4");
storage.add("5");
return new ConcreteIterator( this );
}
}
125
interface Iterator {
Object first() throws IndexOutOfBoundsException;
Object next() throws IndexOutOfBoundsException;
boolean isDone();
Object currentItem() throws IndexOutOfBoundsException;
}
class ConcreteIterator implements Iterator {
private ConcreteAggregate aggregate;
private int index = 0;
public ConcreteIterator( ConcreteAggregate aggregate ){
this.aggregate = aggregate;
}
public Object first()
throws IndexOutOfBoundsException{
Object object = null;
if( !aggregate.storage.isEmpty() ){
index = 0;
object = aggregate.storage.firstElement();
}
126
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
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
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
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
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
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
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
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
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
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
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
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
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
Strategy:
Class diagram:
140
Implementation:
package com.designpattern.learning.stratergypattern;
interface IStratergy{
public void execute();
}
class AlgorithmA implements IStratergy{
public void execute(){
System.out.println("Algorithm:A");
}
} 141
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
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
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
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
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
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
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
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
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
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
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
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
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
state = new GrantPermission();
context.setPermission( state );
System.out.println( context.request());
state = new RevokePermission();
context.setPermission( state );
System.out.println( context.request());
}
}
155
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
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
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
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
Class diagram:
160
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
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
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
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
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
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
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
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
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
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
Class diagram:
171
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
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
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
• 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
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
Class diagram
177
+visit(in visitor : Car)
+visit(in visit : Body)
+visit(in visit : Wheel)
+visit(in engine : Engine)
«interface»
Visitor
+accept(in Visitor : Visitor)
«interface»
CarElement
CostFindVisitor SpecificationVisitor
+getWheelCost() : int
+getSpecification() : String
+accept(in Visitor : Visitor) : void
-wheelCost
-specification
Wheel
Client
+getElements() : CarElement
-elements
Car
+getBodyCost() : int
+getSpecification() : String
+accept(in visitor : Visitor)
-bodyCost
-specifcation
Body
+getEngineCost() : int
+getSpecification() : String
+accept(in visitor : Visitor)
-engineCost : int
-specification : String
Engine
1 *
178
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
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
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
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
public CarElement [] getElements() {
return elements;
}
}
visitor.java
package com.designpattern.learning.visitorpattern.example2;
interface Visitor {
void visit (Wheel wheel);
void visit (Engine engine);
void visit (Body body);
void visit (Car car);
}
CostFindVisitor.java
package com.designpattern.learning.visitorpattern.example2;
public class CostFindVisitor implements Visitor{
private int totalCost =0;
public void visit (Wheel wheel) {
totalCost += wheel.getCost();
}
183
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);
}
}
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
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
187
https://www.quora.com/What-is-a-simple-metaphor-or-analogy-to-explain-what-is-
prototype-based-programming
http://www.oodesign.com/
http://www.journaldev.com/1827/java-design-patterns-example-tutorial
https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm
https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-
core-libraries
https://www.javatpoint.com/design-patterns-in-java
http://www.vogella.com/tutorials/DesignPatterns/article.html
www.google.com
http://www.allapplabs.com/java_design_patterns
https://sourcemaking.com/design_patterns
http://javapapers.com/design-patterns/
https://javarevealed.wordpress.com/
https://en.wikipedia.org/wiki/Facade_pattern
https://neillmorgan.wordpress.com/2010/02/07/observer-pattern-pros-cons/
References

More Related Content

What's hot

Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Write your Helm charts as a professional. Design templates and inheritance. B...
Write your Helm charts as a professional. Design templates and inheritance. B...Write your Helm charts as a professional. Design templates and inheritance. B...
Write your Helm charts as a professional. Design templates and inheritance. B...
Volodymyr Shynkar
 
Angular
AngularAngular
Repository Management with JFrog Artifactory
Repository Management with JFrog ArtifactoryRepository Management with JFrog Artifactory
Repository Management with JFrog Artifactory
Stephen Chin
 
Design patterns
Design patternsDesign patterns
Design patterns
abhisheksagi
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
Git and git flow
Git and git flowGit and git flow
Git and git flow
Fran García
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
Tracy Lee
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
A testing strategy for hexagonal applications
A testing strategy for hexagonal applicationsA testing strategy for hexagonal applications
A testing strategy for hexagonal applications
Matthias Noback
 
Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?
confluent
 
Apache Kafka 0.8 basic training - Verisign
Apache Kafka 0.8 basic training - VerisignApache Kafka 0.8 basic training - Verisign
Apache Kafka 0.8 basic training - Verisign
Michael Noll
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
IndicThreads
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
Ratnala Charan kumar
 
Migration d'une Architecture Microservice vers une Architecture Event-Driven ...
Migration d'une Architecture Microservice vers une Architecture Event-Driven ...Migration d'une Architecture Microservice vers une Architecture Event-Driven ...
Migration d'une Architecture Microservice vers une Architecture Event-Driven ...
Daniel Rene FOUOMENE PEWO
 
Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
Git - Basic Crash Course
Git - Basic Crash CourseGit - Basic Crash Course
Git - Basic Crash Course
Nilay Binjola
 
TypeScript
TypeScriptTypeScript
TypeScript
Fabian Vilers
 
Dealing with Merge Conflicts in Git
Dealing with Merge Conflicts in GitDealing with Merge Conflicts in Git
Dealing with Merge Conflicts in Git
gittower
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-data
Lhouceine OUHAMZA
 

What's hot (20)

Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Write your Helm charts as a professional. Design templates and inheritance. B...
Write your Helm charts as a professional. Design templates and inheritance. B...Write your Helm charts as a professional. Design templates and inheritance. B...
Write your Helm charts as a professional. Design templates and inheritance. B...
 
Angular
AngularAngular
Angular
 
Repository Management with JFrog Artifactory
Repository Management with JFrog ArtifactoryRepository Management with JFrog Artifactory
Repository Management with JFrog Artifactory
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
Git and git flow
Git and git flowGit and git flow
Git and git flow
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
A testing strategy for hexagonal applications
A testing strategy for hexagonal applicationsA testing strategy for hexagonal applications
A testing strategy for hexagonal applications
 
Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?
 
Apache Kafka 0.8 basic training - Verisign
Apache Kafka 0.8 basic training - VerisignApache Kafka 0.8 basic training - Verisign
Apache Kafka 0.8 basic training - Verisign
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
 
Migration d'une Architecture Microservice vers une Architecture Event-Driven ...
Migration d'une Architecture Microservice vers une Architecture Event-Driven ...Migration d'une Architecture Microservice vers une Architecture Event-Driven ...
Migration d'une Architecture Microservice vers une Architecture Event-Driven ...
 
Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)
 
Git - Basic Crash Course
Git - Basic Crash CourseGit - Basic Crash Course
Git - Basic Crash Course
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Dealing with Merge Conflicts in Git
Dealing with Merge Conflicts in GitDealing with Merge Conflicts in Git
Dealing with Merge Conflicts in Git
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-data
 

Viewers also liked

Dao benchmark
Dao benchmarkDao benchmark
Dao benchmark
Mallikarjuna G D
 
Sql implementations
Sql implementationsSql implementations
Sql implementations
Mallikarjuna G D
 
Installer benchmarking
Installer benchmarkingInstaller benchmarking
Installer benchmarking
Mallikarjuna G D
 
Cloud computing
Cloud computingCloud computing
Cloud computing
Mallikarjuna G D
 
Maven
MavenMaven
Jdbc
JdbcJdbc
Ide benchmarking
Ide benchmarkingIde benchmarking
Ide benchmarking
Mallikarjuna G D
 
Web services engine
Web services engineWeb services engine
Web services engine
Mallikarjuna G D
 
Project excursion career_orientation
Project excursion career_orientationProject excursion career_orientation
Project excursion career_orientation
Mallikarjuna G D
 
Training
TrainingTraining
Digital marketing
Digital marketingDigital marketing
Digital marketing
Mallikarjuna G D
 
SlideShare 101
SlideShare 101SlideShare 101
SlideShare 101
Amit Ranjan
 

Viewers also liked (12)

Dao benchmark
Dao benchmarkDao benchmark
Dao benchmark
 
Sql implementations
Sql implementationsSql implementations
Sql implementations
 
Installer benchmarking
Installer benchmarkingInstaller benchmarking
Installer benchmarking
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Maven
MavenMaven
Maven
 
Jdbc
JdbcJdbc
Jdbc
 
Ide benchmarking
Ide benchmarkingIde benchmarking
Ide benchmarking
 
Web services engine
Web services engineWeb services engine
Web services engine
 
Project excursion career_orientation
Project excursion career_orientationProject excursion career_orientation
Project excursion career_orientation
 
Training
TrainingTraining
Training
 
Digital marketing
Digital marketingDigital marketing
Digital marketing
 
SlideShare 101
SlideShare 101SlideShare 101
SlideShare 101
 

Similar to Design pattern

Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
Priyanka Pradhan
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - Introduction
Mudasir Qazi
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questions
jinaldesailive
 
Design Pattern in Swift Ch2 Strategy, Decorator
Design Pattern in Swift Ch2 Strategy, DecoratorDesign Pattern in Swift Ch2 Strategy, Decorator
Design Pattern in Swift Ch2 Strategy, Decorator
Chihyang Li
 
JS Design patterns in Web technologies including oop techniques.pptx
JS Design patterns in Web technologies including oop techniques.pptxJS Design patterns in Web technologies including oop techniques.pptx
JS Design patterns in Web technologies including oop techniques.pptx
husnainali397602
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
Santhosh Kumar Srinivasan
 
Design Patterns - GOF
Design Patterns - GOFDesign Patterns - GOF
Design Patterns - GOF
Fanus van Straten
 
Design patterns Structural
Design patterns StructuralDesign patterns Structural
Design patterns Structural
UMAR ALI
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
Design patterns
Design patternsDesign patterns
Design patterns
F(x) Data Labs Pvt Ltd
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Oops design pattern_amitgupta
Oops design pattern_amitguptaOops design pattern_amitgupta
Oops design pattern_amitgupta
Amit Gupta, MCSD TOGAF
 
Nodejs Chapter 3 - Design Pattern
Nodejs Chapter 3 - Design PatternNodejs Chapter 3 - Design Pattern
Nodejs Chapter 3 - Design Pattern
Talentica Software
 
Agile cards
Agile cardsAgile cards
Agile cards
Lapo Cioni
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
C Meenakshi Meyyappan
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
stanbridge
 
Design pattern of software words computer .pptx
Design pattern of software words computer .pptxDesign pattern of software words computer .pptx
Design pattern of software words computer .pptx
muslimpari2503
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.ppt
CSEC5
 
Segue to design patterns
Segue to design patternsSegue to design patterns
Segue to design patterns
Rahul Singh
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 

Similar to Design pattern (20)

Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - Introduction
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questions
 
Design Pattern in Swift Ch2 Strategy, Decorator
Design Pattern in Swift Ch2 Strategy, DecoratorDesign Pattern in Swift Ch2 Strategy, Decorator
Design Pattern in Swift Ch2 Strategy, Decorator
 
JS Design patterns in Web technologies including oop techniques.pptx
JS Design patterns in Web technologies including oop techniques.pptxJS Design patterns in Web technologies including oop techniques.pptx
JS Design patterns in Web technologies including oop techniques.pptx
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Design Patterns - GOF
Design Patterns - GOFDesign Patterns - GOF
Design Patterns - GOF
 
Design patterns Structural
Design patterns StructuralDesign patterns Structural
Design patterns Structural
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Oops design pattern_amitgupta
Oops design pattern_amitguptaOops design pattern_amitgupta
Oops design pattern_amitgupta
 
Nodejs Chapter 3 - Design Pattern
Nodejs Chapter 3 - Design PatternNodejs Chapter 3 - Design Pattern
Nodejs Chapter 3 - Design Pattern
 
Agile cards
Agile cardsAgile cards
Agile cards
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
 
Design pattern of software words computer .pptx
Design pattern of software words computer .pptxDesign pattern of software words computer .pptx
Design pattern of software words computer .pptx
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.ppt
 
Segue to design patterns
Segue to design patternsSegue to design patterns
Segue to design patterns
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 

More from Mallikarjuna G D

Reactjs
ReactjsReactjs
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
Mallikarjuna G D
 
CSS
CSSCSS
Angular 2.0
Angular  2.0Angular  2.0
Angular 2.0
Mallikarjuna G D
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
Mallikarjuna G D
 
Hibernate
HibernateHibernate
Hibernate
Mallikarjuna G D
 
Jspprogramming
JspprogrammingJspprogramming
Jspprogramming
Mallikarjuna G D
 
Servlet programming
Servlet programmingServlet programming
Servlet programming
Mallikarjuna G D
 
Servlet programming
Servlet programmingServlet programming
Servlet programming
Mallikarjuna G D
 
Mmg logistics edu-final
Mmg  logistics edu-finalMmg  logistics edu-final
Mmg logistics edu-final
Mallikarjuna G D
 
Interview preparation net_asp_csharp
Interview preparation net_asp_csharpInterview preparation net_asp_csharp
Interview preparation net_asp_csharp
Mallikarjuna G D
 
Interview preparation devops
Interview preparation devopsInterview preparation devops
Interview preparation devops
Mallikarjuna G D
 
Interview preparation testing
Interview preparation testingInterview preparation testing
Interview preparation testing
Mallikarjuna G D
 
Interview preparation data_science
Interview preparation data_scienceInterview preparation data_science
Interview preparation data_science
Mallikarjuna G D
 
Interview preparation full_stack_java
Interview preparation full_stack_javaInterview preparation full_stack_java
Interview preparation full_stack_java
Mallikarjuna G D
 
Enterprunership
EnterprunershipEnterprunership
Enterprunership
Mallikarjuna G D
 
Core java
Core javaCore java
Core java
Mallikarjuna G D
 
Type script
Type scriptType script
Type script
Mallikarjuna G D
 
Angularj2.0
Angularj2.0Angularj2.0
Angularj2.0
Mallikarjuna G D
 
Git Overview
Git OverviewGit Overview
Git Overview
Mallikarjuna G D
 

More from Mallikarjuna G D (20)

Reactjs
ReactjsReactjs
Reactjs
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
CSS
CSSCSS
CSS
 
Angular 2.0
Angular  2.0Angular  2.0
Angular 2.0
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Hibernate
HibernateHibernate
Hibernate
 
Jspprogramming
JspprogrammingJspprogramming
Jspprogramming
 
Servlet programming
Servlet programmingServlet programming
Servlet programming
 
Servlet programming
Servlet programmingServlet programming
Servlet programming
 
Mmg logistics edu-final
Mmg  logistics edu-finalMmg  logistics edu-final
Mmg logistics edu-final
 
Interview preparation net_asp_csharp
Interview preparation net_asp_csharpInterview preparation net_asp_csharp
Interview preparation net_asp_csharp
 
Interview preparation devops
Interview preparation devopsInterview preparation devops
Interview preparation devops
 
Interview preparation testing
Interview preparation testingInterview preparation testing
Interview preparation testing
 
Interview preparation data_science
Interview preparation data_scienceInterview preparation data_science
Interview preparation data_science
 
Interview preparation full_stack_java
Interview preparation full_stack_javaInterview preparation full_stack_java
Interview preparation full_stack_java
 
Enterprunership
EnterprunershipEnterprunership
Enterprunership
 
Core java
Core javaCore java
Core java
 
Type script
Type scriptType script
Type script
 
Angularj2.0
Angularj2.0Angularj2.0
Angularj2.0
 
Git Overview
Git OverviewGit Overview
Git Overview
 

Recently uploaded

DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY N...
DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY N...DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY N...
DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY N...
thanhluan21
 
(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening
MJDuyan
 
Individual Performance Commitment Review Form-Developmental Plan.docx
Individual Performance Commitment Review Form-Developmental Plan.docxIndividual Performance Commitment Review Form-Developmental Plan.docx
Individual Performance Commitment Review Form-Developmental Plan.docx
monicaaringo1
 
NLC Grade 3.................................... ppt.pptx
NLC Grade 3.................................... ppt.pptxNLC Grade 3.................................... ppt.pptx
NLC Grade 3.................................... ppt.pptx
MichelleDeLaCruz93
 
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdfThe Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
JackieSparrow3
 
AI_in_HR_Presentation Part 1 2024 0703.pdf
AI_in_HR_Presentation Part 1 2024 0703.pdfAI_in_HR_Presentation Part 1 2024 0703.pdf
AI_in_HR_Presentation Part 1 2024 0703.pdf
SrimanigandanMadurai
 
How To Update One2many Field From OnChange of Field in Odoo 17
How To Update One2many Field From OnChange of Field in Odoo 17How To Update One2many Field From OnChange of Field in Odoo 17
How To Update One2many Field From OnChange of Field in Odoo 17
Celine George
 
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024
Elizabeth Walsh
 
How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17
Celine George
 
Split Shifts From Gantt View in the Odoo 17
Split Shifts From Gantt View in the  Odoo 17Split Shifts From Gantt View in the  Odoo 17
Split Shifts From Gantt View in the Odoo 17
Celine George
 
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Brajeswar Paul
 
How to Create a New Article in Knowledge App in Odoo 17
How to Create a New Article in Knowledge App in Odoo 17How to Create a New Article in Knowledge App in Odoo 17
How to Create a New Article in Knowledge App in Odoo 17
Celine George
 
NLC English 7 Consolidation Lesson plan for teacher
NLC English 7 Consolidation Lesson plan for teacherNLC English 7 Consolidation Lesson plan for teacher
NLC English 7 Consolidation Lesson plan for teacher
AngelicaLubrica
 
SEQUNCES Lecture_Notes_Unit4_chapter11_sequence
SEQUNCES  Lecture_Notes_Unit4_chapter11_sequenceSEQUNCES  Lecture_Notes_Unit4_chapter11_sequence
SEQUNCES Lecture_Notes_Unit4_chapter11_sequence
Murugan Solaiyappan
 
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptxBRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
kambal1234567890
 
Edukasyong Pantahanan at Pangkabuhayan 1: Personal Hygiene
Edukasyong Pantahanan at  Pangkabuhayan 1: Personal HygieneEdukasyong Pantahanan at  Pangkabuhayan 1: Personal Hygiene
Edukasyong Pantahanan at Pangkabuhayan 1: Personal Hygiene
MJDuyan
 
National Learning Camp Grade 7 ENGLISH 7-LESSON 7.pptx
National Learning Camp Grade 7 ENGLISH 7-LESSON 7.pptxNational Learning Camp Grade 7 ENGLISH 7-LESSON 7.pptx
National Learning Camp Grade 7 ENGLISH 7-LESSON 7.pptx
EdsNatividad
 
NAEYC Code of Ethical Conduct Resource Book
NAEYC Code of Ethical Conduct Resource BookNAEYC Code of Ethical Conduct Resource Book
NAEYC Code of Ethical Conduct Resource Book
lakitawilson
 
Delegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use CasesDelegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use Cases
Celine George
 
Webinar Innovative assessments for SOcial Emotional Skills
Webinar Innovative assessments for SOcial Emotional SkillsWebinar Innovative assessments for SOcial Emotional Skills
Webinar Innovative assessments for SOcial Emotional Skills
EduSkills OECD
 

Recently uploaded (20)

DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY N...
DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY N...DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY N...
DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY N...
 
(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening
 
Individual Performance Commitment Review Form-Developmental Plan.docx
Individual Performance Commitment Review Form-Developmental Plan.docxIndividual Performance Commitment Review Form-Developmental Plan.docx
Individual Performance Commitment Review Form-Developmental Plan.docx
 
NLC Grade 3.................................... ppt.pptx
NLC Grade 3.................................... ppt.pptxNLC Grade 3.................................... ppt.pptx
NLC Grade 3.................................... ppt.pptx
 
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdfThe Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
 
AI_in_HR_Presentation Part 1 2024 0703.pdf
AI_in_HR_Presentation Part 1 2024 0703.pdfAI_in_HR_Presentation Part 1 2024 0703.pdf
AI_in_HR_Presentation Part 1 2024 0703.pdf
 
How To Update One2many Field From OnChange of Field in Odoo 17
How To Update One2many Field From OnChange of Field in Odoo 17How To Update One2many Field From OnChange of Field in Odoo 17
How To Update One2many Field From OnChange of Field in Odoo 17
 
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024
 
How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17
 
Split Shifts From Gantt View in the Odoo 17
Split Shifts From Gantt View in the  Odoo 17Split Shifts From Gantt View in the  Odoo 17
Split Shifts From Gantt View in the Odoo 17
 
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
 
How to Create a New Article in Knowledge App in Odoo 17
How to Create a New Article in Knowledge App in Odoo 17How to Create a New Article in Knowledge App in Odoo 17
How to Create a New Article in Knowledge App in Odoo 17
 
NLC English 7 Consolidation Lesson plan for teacher
NLC English 7 Consolidation Lesson plan for teacherNLC English 7 Consolidation Lesson plan for teacher
NLC English 7 Consolidation Lesson plan for teacher
 
SEQUNCES Lecture_Notes_Unit4_chapter11_sequence
SEQUNCES  Lecture_Notes_Unit4_chapter11_sequenceSEQUNCES  Lecture_Notes_Unit4_chapter11_sequence
SEQUNCES Lecture_Notes_Unit4_chapter11_sequence
 
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptxBRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
 
Edukasyong Pantahanan at Pangkabuhayan 1: Personal Hygiene
Edukasyong Pantahanan at  Pangkabuhayan 1: Personal HygieneEdukasyong Pantahanan at  Pangkabuhayan 1: Personal Hygiene
Edukasyong Pantahanan at Pangkabuhayan 1: Personal Hygiene
 
National Learning Camp Grade 7 ENGLISH 7-LESSON 7.pptx
National Learning Camp Grade 7 ENGLISH 7-LESSON 7.pptxNational Learning Camp Grade 7 ENGLISH 7-LESSON 7.pptx
National Learning Camp Grade 7 ENGLISH 7-LESSON 7.pptx
 
NAEYC Code of Ethical Conduct Resource Book
NAEYC Code of Ethical Conduct Resource BookNAEYC Code of Ethical Conduct Resource Book
NAEYC Code of Ethical Conduct Resource Book
 
Delegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use CasesDelegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use Cases
 
Webinar Innovative assessments for SOcial Emotional Skills
Webinar Innovative assessments for SOcial Emotional SkillsWebinar Innovative assessments for SOcial Emotional Skills
Webinar Innovative assessments for SOcial Emotional Skills
 

Design pattern

  • 1. June 25, 2017 www.snipe.co.in 1 Prepared :Mallikarjuna G D Email: gdmallikarjuna@gmail.com
  • 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
  • 7. Java & J2EE patterns 1. Fundamental Design Patterns Delegation, Interface, Abstract Superclass, Interface and Abstract class, Immutable, Marker Interface, proxy 2. GRASP(General Responsibility Assignment Software Pattern) Low coupling&High cohesion,Expert, Creator, Polymorphism, pure fabrication, law of delemeter, controller. 3. Creational Pattern Factory Method,Abstract Factory, Builder, Prototype, singleton, object pool 4. Partiioning patterns(Divide and Conquer patterns) Filter,Composite, Read-only Interface. 5. Structural Patterns Adapter, Iterator, Bridge, Facade, Fly weight, Decorator, Virtual Proxy, Dynamic Linkage, Cache Management 6. Behavioral Patterns Chain of Responsibility, command, Mediator, Observer, strategy, Template method, visitor, interpreter, memento, state, Null object. 7
  • 8. 7. concurrency patterns Single Thread Execution, Lock object, Guarded Suspension, Balking , scheduler, Read/write Lock, Producer-consumer, Two-phase termination, Double buffering, Asynchronous processing, Future, session object, lock file, static locking order, optimistic concurrency, thread pool, ephermal cache item,Transmission stack state 8. GUI Design pattern window per task, Interaction style, Explorable interface, conversational text, Selection, Form, Direct Manipulation, Limited Selection size, Ephermal feedback, Disabled Irrelevant things, supplementary window, step-by-step Instructor 9. Organizational Coding patterns Accessor Method Name, Anonymous Adapter, Symbolic Constant Name Define Constants in Interfaces,Switch,Extend Super,Intention Revealing method Conditional Compilation, Composed Method, Checked versus Unchecked Exceptions Convert Exceptions, Server Socket,Client Socket 10. Code Optimization patterns Hashed Adapter Objects, Lazy Initialization, Double checked Locking, Loop unrolling, Lookup Table 12.Testing Patterns Black Box Testing, White Box Testing,Unit Testing, Integration Testing, System Testing, Regression Testing, Acceptance Testing, Clean Room Testing 8
  • 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
  • 27. Class diagram: +Connection() +description() : String Connection +OracleConnection() +description() : String OracleConnection +SQLServerConnection() +description() : String SQLServerConnection +MySQLServerConnection() +description() : String MySQLServerConnection +FactoryPattern() +CreateConnection() #type : String FactoryPattern +callFactoryMethod() TestFactoryPattern 27
  • 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
  • 43. Implementation: package com.learning.designpattern.PrototypePattern; import java.util.Hashtable; abstract class Product implements Cloneable { private String productCode; private String description; public Object clone(){ Object clone = null; try{ clone = super.clone(); }catch(Exception e){ e.printStackTrace(); } return clone; } public String getProductCode() { return productCode; } public void setProductCode (String productCode) { this.productCode = productCode; } public String getDescription() { return description; } public void setDescription (String description) { this.description = description; } }
  • 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
  • 46. public class Application{ public static void main(String args[]){ ProductCache.loadCache(); Book clonedBook = (Book) ProductCache.getProduct("Prod1"); System.out.println("Product Code = " + clonedBook.getProductCode()); System.out.println("Description = " + clonedBook.getDescription()); System.out.println("Pages" + clonedBook.getNumberOfPages()); DVD clonedDVD = (DVD) ProductCache.getProduct("Prod2"); System.out.println("Product Code = " + clonedDVD.getProductCode()); System.out.println("Description = " + clonedDVD.getDescription()); System.out.println("Duration = " + clonedDVD.getDuration()); } } 46
  • 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
  • 59. public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } -- package com.designpattern.learning.adapterpattern; public class AdapterObject implements SecondObjectInterface{ private FirstObject firstObject; private String firstName; private String lastName; AdapterObject(FirstObject firstObject){ this.firstObject = firstObject; firstName = firstObject.getName().split (" ")[0]; lastName = firstObject.getName().split (" ")[1]; } 59
  • 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();
  • 77. compGraphic1.add(circle1); compGraphic2.add(circle2); compGraphic3.add(circle3); compGraphic1.add(compGraphic2); compGraphic1.add(compGraphic2); compGraphic1.add(elipse); //print compGraphic1.print(); compGraphic2.print(); compGraphic3.print(); circle4.print(); } } Applicability: – When you want to represent the whole hierarchy or a part of the hierarchy of objects. – When you want clients to be able to ignore the differences between compositions of objects and individual objects. – When the structure can have any level of complexity and is dynamic.
  • 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).
  • 82. Implementation: package com.learning.designpattern.FlyweightPattern; import java.util.Hashtable; class StudentFlyweight{ float avg; StudentFlyweight(float avg){ this.avg = avg; } } class Student extends StudentFlyweight{ private String name; private float score; private float standing = 0.0f; Student(float avg){ super(avg); }
  • 83. public String getName() { return name; } public void setName(String name) { this.name = name; } public float getScore () { return score; } public void setScore (float score) { this.score = score; } public float getStanding() { return score /(avg-1.0f)*100.0f; } }
  • 84. class FlyweightFactory{ private Hashtable flyweights = new Hashtable(); public Student getFlyweight( Object key, float avg ){ Student flyweight = (Student) flyweights.get (key); if( flyweight == null ){ flyweight = new Student(avg); flyweights.put( key, flyweight); } return flyweight; } } public class TestFlyweight { public static void main(String args[]){ String name[] ={"Swamy", "Mohan", "Ram"}; float score[] = {44.5f,22.3f,67.0f}; float total =0.0f; for(int loop=0;loop<score.length; loop++){ total = total + score[loop]; }
  • 85. float avg = total/score.length; FlyweightFactory factory = new FlyweightFactory(); Student student = factory.getFlyweight ("Mallik",avg); System.out.println("STUDENT INFO"); for(int numStundent = 0; numStundent< name.length; numStundent++){ student.setName (name[numStundent]); student.setScore (score[numStundent]); System.out.println (student.getName()+" "+student.getScore()+ " "+student.getStanding()); } } }
  • 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
  • 112. implementation package com.designpattern.learning.observerpattern; import java.util.ArrayList; import java.util.List; abstract class Subscriber{ public Publisher sub; public abstract void update(); } 112 Client +addObserver() : Subscriber +removeObserver() : Subscriber +getState() : double +setState() : void -state : double +observers : Subscriber Publisher +update() : void Subscriber -update() : void CeilSubscriber -update() : void FloorSubscriber -update() : void SqrtSubscriber 1 *
  • 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
  • 119. Class diagram: package com.designpattern.learning.chainOfResponsibility; class Handler { private Handler successor; public void setSuccessor( Handler successor ){ this.successor = successor; } public Handler getSuccessor(){ return successor; } public void handleRequest(){ successor.handleRequest(); } } 119
  • 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
  • 125. Implementation: interface Aggregate { Iterator createIterator(); } class ConcreteAggregate implements Aggregate { public Vector storage = new Vector(); public Iterator createIterator(){ storage.add("1"); storage.add("2"); storage.add("3"); storage.add("4"); storage.add("5"); return new ConcreteIterator( this ); } } 125
  • 126. interface Iterator { Object first() throws IndexOutOfBoundsException; Object next() throws IndexOutOfBoundsException; boolean isDone(); Object currentItem() throws IndexOutOfBoundsException; } class ConcreteIterator implements Iterator { private ConcreteAggregate aggregate; private int index = 0; public ConcreteIterator( ConcreteAggregate aggregate ){ this.aggregate = aggregate; } public Object first() throws IndexOutOfBoundsException{ Object object = null; if( !aggregate.storage.isEmpty() ){ index = 0; object = aggregate.storage.firstElement(); } 126
  • 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
  • 141. Implementation: package com.designpattern.learning.stratergypattern; interface IStratergy{ public void execute(); } class AlgorithmA implements IStratergy{ public void execute(){ System.out.println("Algorithm:A"); } } 141
  • 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
  • 178. +visit(in visitor : Car) +visit(in visit : Body) +visit(in visit : Wheel) +visit(in engine : Engine) «interface» Visitor +accept(in Visitor : Visitor) «interface» CarElement CostFindVisitor SpecificationVisitor +getWheelCost() : int +getSpecification() : String +accept(in Visitor : Visitor) : void -wheelCost -specification Wheel Client +getElements() : CarElement -elements Car +getBodyCost() : int +getSpecification() : String +accept(in visitor : Visitor) -bodyCost -specifcation Body +getEngineCost() : int +getSpecification() : String +accept(in visitor : Visitor) -engineCost : int -specification : String Engine 1 * 178
  • 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
  • 183. public CarElement [] getElements() { return elements; } } visitor.java package com.designpattern.learning.visitorpattern.example2; interface Visitor { void visit (Wheel wheel); void visit (Engine engine); void visit (Body body); void visit (Car car); } CostFindVisitor.java package com.designpattern.learning.visitorpattern.example2; public class CostFindVisitor implements Visitor{ private int totalCost =0; public void visit (Wheel wheel) { totalCost += wheel.getCost(); } 183
  • 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
  • 187. 187 https://www.quora.com/What-is-a-simple-metaphor-or-analogy-to-explain-what-is- prototype-based-programming http://www.oodesign.com/ http://www.journaldev.com/1827/java-design-patterns-example-tutorial https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas- core-libraries https://www.javatpoint.com/design-patterns-in-java http://www.vogella.com/tutorials/DesignPatterns/article.html www.google.com http://www.allapplabs.com/java_design_patterns https://sourcemaking.com/design_patterns http://javapapers.com/design-patterns/ https://javarevealed.wordpress.com/ https://en.wikipedia.org/wiki/Facade_pattern https://neillmorgan.wordpress.com/2010/02/07/observer-pattern-pros-cons/ References