SlideShare uma empresa Scribd logo
1 de 54
Unit 2-Design
Patterns
2
Books
 Design Patterns : Elements of Reusable Object-Oriented Software
(1995)
 (The-Gang-of-Four Book)
 The-Gang-of-Four (GoF) - Gamma, Helm, Johnson , Vlissides
 Analysis Patterns - Reusable Object Models (1997)
 Martin Fowler
 The Design Patterns Smalltalk Companion (1998)
 Alpert, Brown & Woolf
UML class diagram recall
Concrete
Abstract
Interface
# private
* protected
+ public
static
# private()
* protected()
+ public()
abstract()
static()
name(Type1, Type2) :
RetType
code
3
Packag
e
Class1
Class2
ClassN
derived
aggregato
r
creator
caller/use
base
aggregate
e
product
callee/use
What is a Design Pattern?
A design pattern is a general reusable solution to
a commonly occurring problem in software design.
A design pattern is not a finished design that can
be transformed directly into code. It is a
description or template for how to solve a
problem that can be used in many different
situations.
Object-oriented design patterns typically show
relationships and interactions between classes
or objects, without specifying the final application
4
Why Design Patterns?
 Design patterns support object-oriented reuse at a high level of
abstraction
 Design patterns provide a “framework” that guides and constrains
object-oriented implementation
4 Essential Elements of Design Patterns
Name : identifies a pattern
Problem : describes when to apply the pattern in terms of the
problem and context
Solution : describes elements that make up the design, their
relationships, responsibilities, and collaborations
Consequences : results and trade-offs of applying the pattern
6
Organizing Design Patterns
By Purpose (reflects what a pattern does):
• Creational Patterns
• Structural Patterns
• Behavioral Patterns
By Scope: specifies whether the pattern applies primarily to
 classes or to
 objects.
7
Design Patterns Space
Abstract Factory
Builder
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of
Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
Factory Method Adapter
Interpreter
Template
Creational Structural Behavioral
Object
Class
Scope
Purpose
Creational Patterns
Brent Ramerth
Abstract Factory, Builder
What are creational patterns?
Design patterns that deal with object creation mechanisms, trying
to create objects in a manner suitable to the situation. The
Creational pattern show how to make the software design
flexible.
There are 5 well known design patterns that are part of creational
pattern. These are-
Abstract Factory pattern – is for creating the instances of several
families of classes
Factory method pattern- is for creating the instances of several
derived classes
Singleton pattern: It ensures that a class has only one instance
and provides global point of access to it
Builder pattern- separates the object construction from its
representation
Prototype pattern- It specifies the kinds of objects to create using a
prototypical instance and create new objects by copying this
prototype.
Benefits of creational patterns
Creational patterns let you program to an
interface defined by an abstract class
That lets you configure a system with
“product” objects that vary widely in
structure and functionality
Example: GUI systems
InterViews GUI class library
Multiple look-and-feels
Abstract Factories for different screen
components
Benefits of creational patterns
Generic instantiation – Objects are instantiated
without having to identify a specific class type in
client code (Abstract Factory, Factory)
Simplicity – Make instantiation easier: callers do not
have to write long complex code to instantiate and
set up an object (Builder, Prototype pattern)
Creation constraints – Creational patterns can put
bounds on who can create objects, how they are
created, and when they are created
Factory Method
Intent: The factory method pattern makes use of factory methods to deal
with the problem of creating objects without specifying the exact class
of the object that will be created.
The interface is defined for creating an object but the subclass decides
which class to instantiate
The advantage of a factory method is that it can return the same instance
multiple times, or can return a subclass rather than an object of that
exact type
Other design patterns require new classes whereas the factory method
only requires new operation
Using Factory method the design can be made customizable
Implementatio
n
<<inteface
Product
ConcreteProduct
Factory
FactoryMethod():Product
MyFunction():Product
Concrete Factory
factoryMethod():Product
The factory class or the
creator class declares a
factoryMethod which returns
the Product object. It is an
abstract class
ConcreteFactory is a child class
which is inherited from the Factory
class for creating the product. It
overrides the factoryMethod for
creating the products
The product is basically an
interface for the objects
that are created by the
factory method
The ConcreteProduct
implements the Product
interface
Sample skeleton
Step1: the interface Product and the ConcreteProduct class is written as follows
Public interface Product
{ // body of interface }
Step2: The client class makes use of ConcereteFactory clss which creates the instance creator, and using this
instance or object the factoryMethod can be invoked in some function say-MyFunction. The
factoryMethod is useful for creating the product objects
Public abstract class Factory
{
protected abstract Product factoryMethod();
Public void myFunction()
{ Product product = factoryMethod(); }
}
Public class ConcreteFactory extends Factory
{
protected Product factoryMethod()
{ return new ConcreteProduct(); // returns object of ConcreteProduct class }
}
Public class Program
{
public static void main (String arg[])
{ Factory creator = new ConcreteFactory();
creator.myFuction();
}
}
Creational-Abstract Factory: An
Example
PIM system
Manage addresses and phone numbers
You hard-coded it for US data
At some point, you wanted to extend it to
incorporate any address / phone number
So you subclassed
DutchAddress, JapanesePhoneNumber, etc.
But now, how do you create them?
Creational-Abstract Factory:
Overview
Intent
Provide an interface for creating families of related or
dependent objects without specifying their concrete
classes
Analogous to a pasta maker
Your code is the pasta maker
Different disks create different pasta shapes:
these are the factories
All disks have certain properties in common
so that they will work with the pasta maker
All pastas have certain characteristics in
common that are inherited from the generic
“Pasta” object
Creational-Abstract Factory:
Participants
AbstractFactory
Declares an interface for operations
that create abstract products
ConcreteFactory
Implements the operations to create
concrete product objects: usually
instantiated as a Singleton
AbstractProduct
Declares an interface for a type of
product object; Concrete Factories
produce the concrete products
ConcreteProduct
Defines a product object to be created
by the corresponding concrete factory
Creational - Abstract Factory:
Applicability
Use Abstract Factory when:
A system should be independent of how its
products are created, composed, and
represented
A system should be configured with one of
multiple families of products
You want to provide a class library of products,
and you want to reveal just their interfaces, not
their implementations
Creational-Abstract Factory: Consequences
Good:
Isolates concrete classes
All manipulation on client-side done through abstract interfaces
Makes exchanging product families easy
Just change the ConcreteFactory
Enforces consistency among products
Bad
Supporting new kinds of products is difficult
Have to reprogram Abstract Factory and all subclasses
But it’s not so bad in dynamically typed languages
Creational-Abstract Factory:
Implementation
Usually should be a Singleton
Define a Factory Method (GoF) in AbstractFactory –
ConcreteFactory then specifies its products by
overriding the factory for each
public class USAddressFactory implements AddressFactory{
public Address createAddress(){
return new USAddress();
}
public PhoneNumber createPhoneNumber(){
return new USPhoneNumber();
}
}
Maybe use Prototype pattern in dynamically typed
languages (e.g. Smalltalk) to simplify creation
Creational-Factory Method
Define an interface for creating an object,
but let subclasses decide which class to
instantiate. Factory Method lets a class
defer instantiation to subclasses.
21
return new ConcreteProduct();
...
Product product =
CreateProduct();
...
Structural Patterns
Brent Ramerth
Abstract Factory, Builder
23
Structural Patterns
 In software engineering, Structural Design patterns are design patterns that
ease the design by identifying a simple way to realize relationships between
entities
 The structural design pattern serves as a blue print for how different classes and
objects are combined to form larger structures
 Structural patterns are just similar to data structures
Composite
Adapter
Bridge
Façade
Proxy
24
Structural Patterns - Adapter
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn’t otherwise because of
incompatible interfaces.
Applicability
 Reuse of an existing class is desired, but the interface does not
match the need.
 Design of a reusable class that cooperates with unrelated or
unforeseen classes, but classes don’t have compatible interfaces.
Intent
25
How to implement Adapter Design pattern
Client
Adapter
+request()
Adaptee
+specialOperation()
Target
+request()
adaptee.specificOperation()
<<interface>>
target
adaptee
Target — defines the domain-specific interface that the client uses.
Client — collaborates with objects conforming to the Target interface.
Adaptee — defines an existing interface that needs adapting.
Adapter — adapts the interface of Adaptee to the Target interface.
Participants
Clients call operations on an
Adapter instance. In turn, the
Adapter calls Adaptee
operations that carry out the
request.
Collaborations
• Client class makes use of Target interface so that it can just call the Request()
method of the Target interface.
• This Adapter class translates the request from the client to the adaptee. This class
translates incompatible interface of Adaptee into interface of Client.
• The Adaptee class provides the functionality that is required by the client
Structural -Adapter Pattern (26.1)
Problem: How to resolve incompatible interfaces, or
how to provide a stable interface to similar
components with different interfaces.
Solution: Convert the original interface of a
component into another interface, through an
intermediate adapter object.
Note: the Adapter pattern is an application of
Polymorphism
Structural -Adapter Pattern (26.1)
Example: POS needs to adapt several kinds of
external third-party services: tax calculators,
credit authorization services, inventory
systems, accounting systems. Each has a
different API which can’t be changed.
Structural -Fig. 26.1
TaxMasterAdapter
getTaxes( Sale ) : List of TaxLineItems
GoodAsGoldTaxPro
Adapter
getTaxes( Sale ) : List of TaxLineItems
«interface»
ITaxCalculatorAdapter
getTaxes( Sale ) : List of TaxLineItems
Adapters use interfaces and
polymorphism to add a level of
indirection to varying APIs in other
components.
SAPAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
...
GreatNorthernAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
...
«interface»
IAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
...
«interface»
IInventoryAdapter
...
«interface»
ICreditAuthorizationService
Adapter
requestApproval(CreditPayment,TerminalID, MerchantID)
...
Structural -Fig. 26.2
:Register : SAPAccountingAdapter
postSale( sale )
makePayment
the Adapter adapts to
interfaces in other components
SOAP over
HTTP
xxx
...
«actor»
: SAPSystem
Structural -Adapter Pattern (26.1)
Note: Adapter pattern follows GRASP
principles: Polymorphism, Protected
Variation, Indirection
See Fig. 26.3 for conceptual connection
among GRASP principles and Adapter
pattern
Structural- 26.3
Low coupling is a way to achieve protection at a
variation point.
Polymorphism is a way to achieve protection at a
variation point, and a way to achieve low coupling.
An indirection is a way to achieve low coupling.
The Adapter design pattern is a kind of Indirection
and a Pure Fabrication, that uses Polymorphism.
Protected Variation
Mechanism
Low Coupling
Mechanism
Indirection
Mechanism
Adapter
Pure
Fabrication
Polymorphism
Example
GoF Design
Patterns
GRASP
Principles
High Cohesion
Mechanism
Structural -Adapter Pattern
Definition
Convert existing interfaces to new interface
Where to use & benefits
Help match an interface
Make unrelated classes work together
Increase transparency of classes
Structural -Adapter Pattern
Example
Adapter from integer Set to integer Priority Queue
Original
Integer set does not support Priority Queue
Using pattern
Adapter provides interface for using Set as Priority
Queue
Add needed functionality in Adapter methods
Structural -Adapter Example
public interface PriorityQueue
{ // Priority Queue
void add(Object o);
int size();
Object removeSmallest();
}
Structural -Adapter Example
public class PriorityQueueAdapter implements PriorityQueue
{
Set s;
PriorityQueueAdapter(Set s) { this.s = s; }
public void add(Object o) { s.add(o); }
int size() { return s.size(); }
public Integer removeSmallest()
{
Integer smallest = Integer.MAX_VALUE;
Iterator it = s.iterator();
while ( it.hasNext() )
{
Integer i = it.next();
if (i.compareTo(smallest) < 0)
smallest = i;
}
s.remove(smallest);
return smallest;
}
}
Structural - Adapter
Convert the interface of a class into
another interface clients expect. Adapter
lets classes work together that couldn't
otherwise because of incompatible
interfaces.
36
_adaptee.SpecificRequest();
37
Structural Patterns - Bridge
Intent:
The Bridge pattern separates or decouples the interface from
implementation without using inheritance
A parallel class hierarchy is used. On one side of the hierarchy there are
abstract interfaces and on the other side there are concrete
implementations
This pattern can be used when the class vary quite often. These changes
can be accommodated very easily without disturbing the rest of the code.
This is because of the fact that the implementation and separated one
38
Structural Patterns – Bridge-Implementation
ConcreteImplementor
<<interface>>
Implementor
<<interface>>
Abstraction
Opr:
Function()
Refined Function()
Refined
Abstraction
operation()
operation()
Defines abstraction interface. Acts as a base
class for other refined classes. Holds the
reference to particular implementation which is
for platform specific functionality
Interface for the
ConcreteImplementor
Normal class which implements the
Implementor Interface.
Normal class which extends the
Interface defined by Abstraction
S.No
Bridge Adapter
1 The bridge pattern is used to decouple as
abstraction class from its implementation
The adapter pattern converts the interface
between classes with less inheritance
2 This patterns can be used when class vary quite
often
This pattern is often used to make existing
classes work with other without modifying their
source code
3 This pattern is used in graphics toolkits that need
to be run on different platforms
This pattern is used when two incompatible
interfaces need to work together
4 The situation in which class vary quite often, the
bridge pattern is used, Due to use of this pattern
the changes can be accommodated very easily
without distributing the rest of the code as the
implementation and interfaces are separated one
The situation in which one class relies upon a
specific interface which is not implemented by
another class, the adapter acts as a translator
between two types
5 The implementation details can be effectively
hidden from the client so that the client can focus
on the behavior desired from the abstraction
If we have several modules implementing the
same functionality and we wrote the adapters
for them, the adapters are implementing the
same interface. 6
6 Due to separation of interface and
implementation it increases the complexity of the
client program
It makes the code complex and difficult to
debug
Behavioral Patterns
Brent Ramerth
Abstract Factory, Builder
• The behavioral design patterns are design patterns that
identify common communication patterns between objects
and realize these patterns. By doing so, these patterns
increase flexibility in carrying out this communication.
• A behavioral pattern explains how objects interact
• It describes how different objects and classes and
messages to each other to make things happen and how
the various tasks are divided among different objects
41
Behavioral Patterns
• Observer – The observer pattern is a pattern that defines
a link between objects so that when one object’s state
changes, all dependent objects are updated
automatically. This pattern allows communication
between objects in a loosely coupled manner.
• Strategy – It encapsulates an algorithm inside a class
• Command
• State
• Visitor
42
Behavioral Patterns - Observer
Define a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updated
automatically.
Intent
 An abstraction has two aspects, one dependent on the other.
 When changing one object requires changing others, and you don’t
know how many objects need changed.
 When an object needs to notify others without knowledge about who
they are.
Applicability
43
Observer
subject
observers
*
update()
ConcreteObserver
attach( observer )
detach( observer )
notify()
Subject
for all o in observers
o.update()
getState()
subjectState
ConcreteSubject
update()
<<interface>>
Observer
observerState :=
subject.getState()
Subject
 Knows its observers, but not their “real” identity. Provides an interface for attaching/detaching observers.
Observer
 Defines an updating interface for objects that should be identified of changes.
ConcreteSubject
 Stores state of interest to ConcreteObserver objects. Sends update notice to observers upon state change.
ConcreteObserver
 Maintains reference to ConcreteSubject (sometimes). Maintains state that must be consistent with
ConcreteSubject. Implements the Observer interface.
 ConcreteSubject notifies observers when changes occur.
 ConcreteObserver may query subject regarding state change.
Collaborations
Participants
44
Behavioral Patterns - Observer
 Subject
 Knows its observers, but not their “real” identity.
 Provides an interface for attaching/detaching observers.
 Observer
 Defines an updating interface for objects that should be identified of changes.
 ConcreteSubject
 Stores state of interest to ConcreteObserver objects.
 Sends update notice to observers upon state change.
 ConcreteObserver
 Maintains reference to ConcreteSubject (sometimes).
 Maintains state that must be consistent with ConcreteSubject.
 Implements the Observer interface.
Participants
 ConcreteSubject notifies observers when changes occur.
 ConcreteObserver may query subject regarding state change.
Collaborations
45
Behavioral Patterns - Observer
Sequence Diagram
subject :
ConcreteSubject
observer1 :
ConcreteObserver
observer2 :
ConcreteObserver
attach( observer1 )
attach( observer2 )
update()
getState()
update()
getState()
notify()
Behavioral-Observer Pattern–Classification&
Applicability
A behavioral (object) pattern:
Concerns objects and their behavior.
Applicability
Vary and reuse 2 different abstractions
independently.
Change to one object requires change in
(one or more) other objects – whose
identity is not necessarily known
Behavioral-Observer Pattern –
Structure
Subject
attach (Observer)
detach (Observer)
Notify ()
Observer
Update()
Concrete Observer
Update()
observerState
Concrete Subject
GetState()
SetState()
subjectState
observers
subject
For all x in observers{
x.Update(); }
observerState=
subject.getState();
Strategy
There are common situations when classes differ
only in their behavior. For this case, is a good idea
to isolate the algorithms in separate classes in
order to have the ability to select different
algorithms at runtime.
This is a kind of design pattern in which a set of
similar algorithms to be defined and encapsulated
in their own classes
Thus this pattern is intended to define a family of
algorithms, encapsulate each of them and make
them interchangeable
Strategy is like Template Method
49
Behavioral Patterns - Strategy
Pattern
Intent: Defines a family of algorithms, encapsulate each one, and
make them interchangeable. Strategy lets the algorithm vary
independently from clients that use it.
 Motivation: when there are many algorithms for solving a problem,
hard-wiring all algorithms in client’s code may have several
problems:
 Clients get fat and harder to maintain
 Different algorithms may be appropriate at different time
 It is difficult to add new algorithms
50
Behavioral Patterns - Strategy
Pattern
Context
ContextInterface()
Strategy
AlgorithmInterface()
ConcreteStrategyB
AlgorithmInterface()
ConcreteStrategyA
AlgorithmInterface()
ConcreteStrategyC
AlgorithmInterface()
strategy
51
Behavioral Patterns - Participants of
Strategy
Strategy: declares an interface common to all supported
algorithm. Context uses this interface to call the algorithm
defined by a ConcreteStrategy.
ConcreteStrategy: implements the algorithm using the Strategy
interface
Context: maintains a reference to a Strategy object and defines
an interface that let Strategy access its data
52
Behavioral Patterns - Sorting Example
Requirement: we want to sort a list of integers using different sorting
algorithms, e.g. quick sort, selection sort, insertion sort, etc.
E.g., {3, 5, 6, 2, 44, 67, 1, 344, ... }
{1, 2, 3, 5, 6, 44, 67, 344, ... }
 One way to solve this problem is to write a function for each sorting
algorithm, e.g.
 quicksort(int[] in, int[] res)
 insertionsort(int[] in, int[] res)
 mergesort(int[] in, int[] res)
 A better way is to use the Strategy pattern
53
Behavioral Patterns - Strategy Pattern
SortedList
SetSortStr(sortStr:SortStrategy)
Sort()
SortStrategy
Sort(list:ArrayList)
InsertionSort
Sort(list:ArrayList)
QuickSort
Sort(list:ArrayList)
MergeSort
Sort(list:ArrayList)
-sortStrategy
Main
Main()
stdRec
-list: ArrayList
Sort()
{sortStrategy.Sort(list)}
How is –sortStrategy implemented?
Main()
{…
stdRec.SetSortStr(sortStrInfo);
stdRec.Sort()}
How is stdRec implemente
Behavioral-Strategy
Define a family of algorithms, encapsulate
each one, and make them interchangeable.
Strategy lets the algorithm vary
independently from clients that use it.
54
_strategy.Algorithm();

Mais conteúdo relacionado

Mais procurados

Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern Nirthika Rajendran
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternMudasir Qazi
 
Presentation facade design pattern
Presentation facade design patternPresentation facade design pattern
Presentation facade design patternBayu Firmawan Paoh
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 

Mais procurados (20)

Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Facade Pattern
Facade PatternFacade Pattern
Facade Pattern
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Iterator
IteratorIterator
Iterator
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Presentation facade design pattern
Presentation facade design patternPresentation facade design pattern
Presentation facade design pattern
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 

Semelhante a Unit 2-Design Patterns.ppt

Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1Shahzad
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examplesQuang Suma
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Luis Valencia
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
Prophecy Of Design Patterns
Prophecy Of Design PatternsProphecy Of Design Patterns
Prophecy Of Design Patternspradeepkothiyal
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa TouchEliah Nikans
 
Factory Pattern
Factory PatternFactory Pattern
Factory PatternDeepti C
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design patternchetankane
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptxSachin Patidar
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsJason Townsend, MBA
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns ExplainedPrabhjit Singh
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of PatternsChris Eargle
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxssuser9a23691
 

Semelhante a Unit 2-Design Patterns.ppt (20)

Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Prophecy Of Design Patterns
Prophecy Of Design PatternsProphecy Of Design Patterns
Prophecy Of Design Patterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Sda 8
Sda   8Sda   8
Sda 8
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design pattern
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design Patterns
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns Explained
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of Patterns
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptx
 

Mais de MsRAMYACSE

Mais de MsRAMYACSE (8)

plant ppt.pptx
plant ppt.pptxplant ppt.pptx
plant ppt.pptx
 
Unit 2.ppt
Unit 2.pptUnit 2.ppt
Unit 2.ppt
 
unit-4.ppt
unit-4.pptunit-4.ppt
unit-4.ppt
 
unit1.ppt
unit1.pptunit1.ppt
unit1.ppt
 
Unit 1.ppt
Unit 1.pptUnit 1.ppt
Unit 1.ppt
 
garden.pptx
garden.pptxgarden.pptx
garden.pptx
 
organ.pptx
organ.pptxorgan.pptx
organ.pptx
 
xen.pptx
xen.pptxxen.pptx
xen.pptx
 

Último

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Último (20)

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Unit 2-Design Patterns.ppt

  • 2. 2 Books  Design Patterns : Elements of Reusable Object-Oriented Software (1995)  (The-Gang-of-Four Book)  The-Gang-of-Four (GoF) - Gamma, Helm, Johnson , Vlissides  Analysis Patterns - Reusable Object Models (1997)  Martin Fowler  The Design Patterns Smalltalk Companion (1998)  Alpert, Brown & Woolf
  • 3. UML class diagram recall Concrete Abstract Interface # private * protected + public static # private() * protected() + public() abstract() static() name(Type1, Type2) : RetType code 3 Packag e Class1 Class2 ClassN derived aggregato r creator caller/use base aggregate e product callee/use
  • 4. What is a Design Pattern? A design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application 4
  • 5. Why Design Patterns?  Design patterns support object-oriented reuse at a high level of abstraction  Design patterns provide a “framework” that guides and constrains object-oriented implementation 4 Essential Elements of Design Patterns Name : identifies a pattern Problem : describes when to apply the pattern in terms of the problem and context Solution : describes elements that make up the design, their relationships, responsibilities, and collaborations Consequences : results and trade-offs of applying the pattern
  • 6. 6 Organizing Design Patterns By Purpose (reflects what a pattern does): • Creational Patterns • Structural Patterns • Behavioral Patterns By Scope: specifies whether the pattern applies primarily to  classes or to  objects.
  • 7. 7 Design Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade Flyweight Proxy Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor Factory Method Adapter Interpreter Template Creational Structural Behavioral Object Class Scope Purpose
  • 9. What are creational patterns? Design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The Creational pattern show how to make the software design flexible. There are 5 well known design patterns that are part of creational pattern. These are- Abstract Factory pattern – is for creating the instances of several families of classes Factory method pattern- is for creating the instances of several derived classes Singleton pattern: It ensures that a class has only one instance and provides global point of access to it Builder pattern- separates the object construction from its representation Prototype pattern- It specifies the kinds of objects to create using a prototypical instance and create new objects by copying this prototype.
  • 10. Benefits of creational patterns Creational patterns let you program to an interface defined by an abstract class That lets you configure a system with “product” objects that vary widely in structure and functionality Example: GUI systems InterViews GUI class library Multiple look-and-feels Abstract Factories for different screen components
  • 11. Benefits of creational patterns Generic instantiation – Objects are instantiated without having to identify a specific class type in client code (Abstract Factory, Factory) Simplicity – Make instantiation easier: callers do not have to write long complex code to instantiate and set up an object (Builder, Prototype pattern) Creation constraints – Creational patterns can put bounds on who can create objects, how they are created, and when they are created
  • 12. Factory Method Intent: The factory method pattern makes use of factory methods to deal with the problem of creating objects without specifying the exact class of the object that will be created. The interface is defined for creating an object but the subclass decides which class to instantiate The advantage of a factory method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type Other design patterns require new classes whereas the factory method only requires new operation Using Factory method the design can be made customizable
  • 13. Implementatio n <<inteface Product ConcreteProduct Factory FactoryMethod():Product MyFunction():Product Concrete Factory factoryMethod():Product The factory class or the creator class declares a factoryMethod which returns the Product object. It is an abstract class ConcreteFactory is a child class which is inherited from the Factory class for creating the product. It overrides the factoryMethod for creating the products The product is basically an interface for the objects that are created by the factory method The ConcreteProduct implements the Product interface
  • 14. Sample skeleton Step1: the interface Product and the ConcreteProduct class is written as follows Public interface Product { // body of interface } Step2: The client class makes use of ConcereteFactory clss which creates the instance creator, and using this instance or object the factoryMethod can be invoked in some function say-MyFunction. The factoryMethod is useful for creating the product objects Public abstract class Factory { protected abstract Product factoryMethod(); Public void myFunction() { Product product = factoryMethod(); } } Public class ConcreteFactory extends Factory { protected Product factoryMethod() { return new ConcreteProduct(); // returns object of ConcreteProduct class } } Public class Program { public static void main (String arg[]) { Factory creator = new ConcreteFactory(); creator.myFuction(); } }
  • 15. Creational-Abstract Factory: An Example PIM system Manage addresses and phone numbers You hard-coded it for US data At some point, you wanted to extend it to incorporate any address / phone number So you subclassed DutchAddress, JapanesePhoneNumber, etc. But now, how do you create them?
  • 16. Creational-Abstract Factory: Overview Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes Analogous to a pasta maker Your code is the pasta maker Different disks create different pasta shapes: these are the factories All disks have certain properties in common so that they will work with the pasta maker All pastas have certain characteristics in common that are inherited from the generic “Pasta” object
  • 17. Creational-Abstract Factory: Participants AbstractFactory Declares an interface for operations that create abstract products ConcreteFactory Implements the operations to create concrete product objects: usually instantiated as a Singleton AbstractProduct Declares an interface for a type of product object; Concrete Factories produce the concrete products ConcreteProduct Defines a product object to be created by the corresponding concrete factory
  • 18. Creational - Abstract Factory: Applicability Use Abstract Factory when: A system should be independent of how its products are created, composed, and represented A system should be configured with one of multiple families of products You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations
  • 19. Creational-Abstract Factory: Consequences Good: Isolates concrete classes All manipulation on client-side done through abstract interfaces Makes exchanging product families easy Just change the ConcreteFactory Enforces consistency among products Bad Supporting new kinds of products is difficult Have to reprogram Abstract Factory and all subclasses But it’s not so bad in dynamically typed languages
  • 20. Creational-Abstract Factory: Implementation Usually should be a Singleton Define a Factory Method (GoF) in AbstractFactory – ConcreteFactory then specifies its products by overriding the factory for each public class USAddressFactory implements AddressFactory{ public Address createAddress(){ return new USAddress(); } public PhoneNumber createPhoneNumber(){ return new USPhoneNumber(); } } Maybe use Prototype pattern in dynamically typed languages (e.g. Smalltalk) to simplify creation
  • 21. Creational-Factory Method Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. 21 return new ConcreteProduct(); ... Product product = CreateProduct(); ...
  • 23. 23 Structural Patterns  In software engineering, Structural Design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities  The structural design pattern serves as a blue print for how different classes and objects are combined to form larger structures  Structural patterns are just similar to data structures Composite Adapter Bridge Façade Proxy
  • 24. 24 Structural Patterns - Adapter Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. Applicability  Reuse of an existing class is desired, but the interface does not match the need.  Design of a reusable class that cooperates with unrelated or unforeseen classes, but classes don’t have compatible interfaces. Intent
  • 25. 25 How to implement Adapter Design pattern Client Adapter +request() Adaptee +specialOperation() Target +request() adaptee.specificOperation() <<interface>> target adaptee Target — defines the domain-specific interface that the client uses. Client — collaborates with objects conforming to the Target interface. Adaptee — defines an existing interface that needs adapting. Adapter — adapts the interface of Adaptee to the Target interface. Participants Clients call operations on an Adapter instance. In turn, the Adapter calls Adaptee operations that carry out the request. Collaborations • Client class makes use of Target interface so that it can just call the Request() method of the Target interface. • This Adapter class translates the request from the client to the adaptee. This class translates incompatible interface of Adaptee into interface of Client. • The Adaptee class provides the functionality that is required by the client
  • 26. Structural -Adapter Pattern (26.1) Problem: How to resolve incompatible interfaces, or how to provide a stable interface to similar components with different interfaces. Solution: Convert the original interface of a component into another interface, through an intermediate adapter object. Note: the Adapter pattern is an application of Polymorphism
  • 27. Structural -Adapter Pattern (26.1) Example: POS needs to adapt several kinds of external third-party services: tax calculators, credit authorization services, inventory systems, accounting systems. Each has a different API which can’t be changed.
  • 28. Structural -Fig. 26.1 TaxMasterAdapter getTaxes( Sale ) : List of TaxLineItems GoodAsGoldTaxPro Adapter getTaxes( Sale ) : List of TaxLineItems «interface» ITaxCalculatorAdapter getTaxes( Sale ) : List of TaxLineItems Adapters use interfaces and polymorphism to add a level of indirection to varying APIs in other components. SAPAccountingAdapter postReceivable( CreditPayment ) postSale( Sale ) ... GreatNorthernAccountingAdapter postReceivable( CreditPayment ) postSale( Sale ) ... «interface» IAccountingAdapter postReceivable( CreditPayment ) postSale( Sale ) ... «interface» IInventoryAdapter ... «interface» ICreditAuthorizationService Adapter requestApproval(CreditPayment,TerminalID, MerchantID) ...
  • 29. Structural -Fig. 26.2 :Register : SAPAccountingAdapter postSale( sale ) makePayment the Adapter adapts to interfaces in other components SOAP over HTTP xxx ... «actor» : SAPSystem
  • 30. Structural -Adapter Pattern (26.1) Note: Adapter pattern follows GRASP principles: Polymorphism, Protected Variation, Indirection See Fig. 26.3 for conceptual connection among GRASP principles and Adapter pattern
  • 31. Structural- 26.3 Low coupling is a way to achieve protection at a variation point. Polymorphism is a way to achieve protection at a variation point, and a way to achieve low coupling. An indirection is a way to achieve low coupling. The Adapter design pattern is a kind of Indirection and a Pure Fabrication, that uses Polymorphism. Protected Variation Mechanism Low Coupling Mechanism Indirection Mechanism Adapter Pure Fabrication Polymorphism Example GoF Design Patterns GRASP Principles High Cohesion Mechanism
  • 32. Structural -Adapter Pattern Definition Convert existing interfaces to new interface Where to use & benefits Help match an interface Make unrelated classes work together Increase transparency of classes
  • 33. Structural -Adapter Pattern Example Adapter from integer Set to integer Priority Queue Original Integer set does not support Priority Queue Using pattern Adapter provides interface for using Set as Priority Queue Add needed functionality in Adapter methods
  • 34. Structural -Adapter Example public interface PriorityQueue { // Priority Queue void add(Object o); int size(); Object removeSmallest(); }
  • 35. Structural -Adapter Example public class PriorityQueueAdapter implements PriorityQueue { Set s; PriorityQueueAdapter(Set s) { this.s = s; } public void add(Object o) { s.add(o); } int size() { return s.size(); } public Integer removeSmallest() { Integer smallest = Integer.MAX_VALUE; Iterator it = s.iterator(); while ( it.hasNext() ) { Integer i = it.next(); if (i.compareTo(smallest) < 0) smallest = i; } s.remove(smallest); return smallest; } }
  • 36. Structural - Adapter Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. 36 _adaptee.SpecificRequest();
  • 37. 37 Structural Patterns - Bridge Intent: The Bridge pattern separates or decouples the interface from implementation without using inheritance A parallel class hierarchy is used. On one side of the hierarchy there are abstract interfaces and on the other side there are concrete implementations This pattern can be used when the class vary quite often. These changes can be accommodated very easily without disturbing the rest of the code. This is because of the fact that the implementation and separated one
  • 38. 38 Structural Patterns – Bridge-Implementation ConcreteImplementor <<interface>> Implementor <<interface>> Abstraction Opr: Function() Refined Function() Refined Abstraction operation() operation() Defines abstraction interface. Acts as a base class for other refined classes. Holds the reference to particular implementation which is for platform specific functionality Interface for the ConcreteImplementor Normal class which implements the Implementor Interface. Normal class which extends the Interface defined by Abstraction
  • 39. S.No Bridge Adapter 1 The bridge pattern is used to decouple as abstraction class from its implementation The adapter pattern converts the interface between classes with less inheritance 2 This patterns can be used when class vary quite often This pattern is often used to make existing classes work with other without modifying their source code 3 This pattern is used in graphics toolkits that need to be run on different platforms This pattern is used when two incompatible interfaces need to work together 4 The situation in which class vary quite often, the bridge pattern is used, Due to use of this pattern the changes can be accommodated very easily without distributing the rest of the code as the implementation and interfaces are separated one The situation in which one class relies upon a specific interface which is not implemented by another class, the adapter acts as a translator between two types 5 The implementation details can be effectively hidden from the client so that the client can focus on the behavior desired from the abstraction If we have several modules implementing the same functionality and we wrote the adapters for them, the adapters are implementing the same interface. 6 6 Due to separation of interface and implementation it increases the complexity of the client program It makes the code complex and difficult to debug
  • 40. Behavioral Patterns Brent Ramerth Abstract Factory, Builder • The behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication. • A behavioral pattern explains how objects interact • It describes how different objects and classes and messages to each other to make things happen and how the various tasks are divided among different objects
  • 41. 41 Behavioral Patterns • Observer – The observer pattern is a pattern that defines a link between objects so that when one object’s state changes, all dependent objects are updated automatically. This pattern allows communication between objects in a loosely coupled manner. • Strategy – It encapsulates an algorithm inside a class • Command • State • Visitor
  • 42. 42 Behavioral Patterns - Observer Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Intent  An abstraction has two aspects, one dependent on the other.  When changing one object requires changing others, and you don’t know how many objects need changed.  When an object needs to notify others without knowledge about who they are. Applicability
  • 43. 43 Observer subject observers * update() ConcreteObserver attach( observer ) detach( observer ) notify() Subject for all o in observers o.update() getState() subjectState ConcreteSubject update() <<interface>> Observer observerState := subject.getState() Subject  Knows its observers, but not their “real” identity. Provides an interface for attaching/detaching observers. Observer  Defines an updating interface for objects that should be identified of changes. ConcreteSubject  Stores state of interest to ConcreteObserver objects. Sends update notice to observers upon state change. ConcreteObserver  Maintains reference to ConcreteSubject (sometimes). Maintains state that must be consistent with ConcreteSubject. Implements the Observer interface.  ConcreteSubject notifies observers when changes occur.  ConcreteObserver may query subject regarding state change. Collaborations Participants
  • 44. 44 Behavioral Patterns - Observer  Subject  Knows its observers, but not their “real” identity.  Provides an interface for attaching/detaching observers.  Observer  Defines an updating interface for objects that should be identified of changes.  ConcreteSubject  Stores state of interest to ConcreteObserver objects.  Sends update notice to observers upon state change.  ConcreteObserver  Maintains reference to ConcreteSubject (sometimes).  Maintains state that must be consistent with ConcreteSubject.  Implements the Observer interface. Participants  ConcreteSubject notifies observers when changes occur.  ConcreteObserver may query subject regarding state change. Collaborations
  • 45. 45 Behavioral Patterns - Observer Sequence Diagram subject : ConcreteSubject observer1 : ConcreteObserver observer2 : ConcreteObserver attach( observer1 ) attach( observer2 ) update() getState() update() getState() notify()
  • 46. Behavioral-Observer Pattern–Classification& Applicability A behavioral (object) pattern: Concerns objects and their behavior. Applicability Vary and reuse 2 different abstractions independently. Change to one object requires change in (one or more) other objects – whose identity is not necessarily known
  • 47. Behavioral-Observer Pattern – Structure Subject attach (Observer) detach (Observer) Notify () Observer Update() Concrete Observer Update() observerState Concrete Subject GetState() SetState() subjectState observers subject For all x in observers{ x.Update(); } observerState= subject.getState();
  • 48. Strategy There are common situations when classes differ only in their behavior. For this case, is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime. This is a kind of design pattern in which a set of similar algorithms to be defined and encapsulated in their own classes Thus this pattern is intended to define a family of algorithms, encapsulate each of them and make them interchangeable Strategy is like Template Method
  • 49. 49 Behavioral Patterns - Strategy Pattern Intent: Defines a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.  Motivation: when there are many algorithms for solving a problem, hard-wiring all algorithms in client’s code may have several problems:  Clients get fat and harder to maintain  Different algorithms may be appropriate at different time  It is difficult to add new algorithms
  • 50. 50 Behavioral Patterns - Strategy Pattern Context ContextInterface() Strategy AlgorithmInterface() ConcreteStrategyB AlgorithmInterface() ConcreteStrategyA AlgorithmInterface() ConcreteStrategyC AlgorithmInterface() strategy
  • 51. 51 Behavioral Patterns - Participants of Strategy Strategy: declares an interface common to all supported algorithm. Context uses this interface to call the algorithm defined by a ConcreteStrategy. ConcreteStrategy: implements the algorithm using the Strategy interface Context: maintains a reference to a Strategy object and defines an interface that let Strategy access its data
  • 52. 52 Behavioral Patterns - Sorting Example Requirement: we want to sort a list of integers using different sorting algorithms, e.g. quick sort, selection sort, insertion sort, etc. E.g., {3, 5, 6, 2, 44, 67, 1, 344, ... } {1, 2, 3, 5, 6, 44, 67, 344, ... }  One way to solve this problem is to write a function for each sorting algorithm, e.g.  quicksort(int[] in, int[] res)  insertionsort(int[] in, int[] res)  mergesort(int[] in, int[] res)  A better way is to use the Strategy pattern
  • 53. 53 Behavioral Patterns - Strategy Pattern SortedList SetSortStr(sortStr:SortStrategy) Sort() SortStrategy Sort(list:ArrayList) InsertionSort Sort(list:ArrayList) QuickSort Sort(list:ArrayList) MergeSort Sort(list:ArrayList) -sortStrategy Main Main() stdRec -list: ArrayList Sort() {sortStrategy.Sort(list)} How is –sortStrategy implemented? Main() {… stdRec.SetSortStr(sortStrInfo); stdRec.Sort()} How is stdRec implemente
  • 54. Behavioral-Strategy Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. 54 _strategy.Algorithm();