0% found this document useful (0 votes)
10 views53 pages

DesignPatternsrev.ppt

The document discusses design patterns, which are essential for creating reusable and flexible object-oriented software solutions. It covers the definition, principles, types, and documentation of design patterns, along with examples like the Adapter pattern. The document emphasizes the importance of understanding design patterns to improve system design and facilitate easier maintenance and documentation.

Uploaded by

Stanford Dias
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views53 pages

DesignPatternsrev.ppt

The document discusses design patterns, which are essential for creating reusable and flexible object-oriented software solutions. It covers the definition, principles, types, and documentation of design patterns, along with examples like the Adapter pattern. The document emphasizes the importance of understanding design patterns to improve system design and facilitate easier maintenance and documentation.

Uploaded by

Stanford Dias
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Design Patterns

Ramrao Wagh
On completion, you will understand
• Need for design patterns
• Define design patterns, essential elements
• Documenting DP
• Design patterns solve design problems
• Principles
• Types of Design Patterns
• Examples of Design Patterns
Introduction
• How to achieve reusable and flexible solution?
• How to differentiate between a Novice and
Experienced Object-Oriented developer?
• OR How to design like an experienced developer?
• REUSE of solutions!
• Recurring patterns
• applied to different problems!

• Results into Flexible, elegant and re-usable


solution
Motivating Example - Adapter

Client Shape
draw()

Line Polygon

draw() draw()

{
//code here
}
Motivating Example - Adapter

Client Drawing circle


Shape
is tedious!
draw()
?
Line Polygon Circle

draw() draw() draw()

{
//code here
}
Motivating Example - Adapter
CircleTwo
Client Shape
draw()
? myDraw()

Line Polygon Circle

draw() draw() draw()

{ Can I use this


//code here implementation
} ?
Motivating Example - Adapter

Object Adapter CircleTwo


Client Shape
draw()
myDraw()

myCircle
Line Polygon Circle

draw() draw() draw()

{ {
//code here myCircle.myDraw()
} }
Motivating Example - Adapter
CircleTwo
Client Shape Class Adapter
myDraw()
draw()

Line Polygon Circle

draw() draw() draw()

{ {
//code here myDraw()
} }
Adapter
• Intent
• Convert the interface of a class into another interface
that clients expect
• Motivation:
• Sometimes you can’t reuse a class because the interface
doesn’t match what is required
• Solution: Adapt the interface:
• Inheriting the correct interface (class adapter pattern)
• May require multiple inheritance (C++), or use of Interfaces (Java)
• Compose an instance within the correct interface (object
adapter pattern)
• Object will implement the interface in terms of the
object’s existing functionality
What Design Patterns can do?
• Record experience in designing object oriented
systems
• Easier to reuse successful designs
• Provide design alternatives that make a system
reusable
• Improve the documentation and maintenance of
existing systems
• Design patterns help a designer get a design
"right" faster
What is a Design Pattern(DP)?
• Descriptions of
communicating objects
and classes that are
customized to solve a
general design problem in
a particular context.
[Gamma]
• A solution to a general
design problem that recurs
frequently
Essential Elements of DP
• Pattern name
• Adapter, Composite, State, Strategy, Factory

• Problem
• When to apply pattern

• Solution
• Design elements

• Consequences
• Results and trade-offs
Documenting Patterns(1)
• Pattern Name and Classification
• conveys the essence of the pattern
• A good name is vital, becomes part of your design
vocabulary
• Intent
• A short statement
• Also Known As
• Other well-known names for the pattern, if any.
• Motivation
• A scenario that illustrates a design problem
• Applicability
• What are the situations in which the design pattern can
be applied?
• Structure
• A graphical representation of the classes in the pattern
Documenting Patterns-(2)
• Participants
• responsibilities

• Collaborations
• Consequences
• Implementation
• Sample Code
• Known Uses
• Related Patterns
How Design Patterns Solve Design Problems
• Find the appropriate objects
• Determine object granularity
• Specify object interfaces
• Specify object implementations
• Put reuse mechanisms to work
• Inheritance vs. composition
• Delegation

• Relate run-time and compile-time structures


• Design for change
Find the appropriate objects
• Objects communicate via Message passing
• Hard part
• decomposing a system into objects

• Plethora of methodologies to identify objects


• Apart from objects from analysis world, there are
additional objects with no counterpart in real
world
• Design should lead to abstraction
• Key to flexible design

• Design pattern finds less-obvious abstractions


Determine Object Granularity
• What should be the granularity of an object?
• Patterns like Façade, flyweight represent large to
small objects
• Describe Specific ways of decomposing an object
into smaller objects
• Abstract Factory, Builder patterns
Specifying Object Interfaces
• Interface
• collection of operation signatures

• Type denotes interface


• Object can have many type and different objects can be of same
type
• Subtypes: Interfaces can have subsets
• Objects are known only through interface

• When a request is sent to an object, the particular operation that's


performed depends on both the request and the receiving object
• Dynamic binding

• Substitute objects that have identical interfaces for each other at


run-time
• Polymorphism

• Design patterns
• help you define interfaces by identifying their key elements and the
kinds of data that get sent across an interface
• specify relationships between interfaces
Specifying Object Implementations
• Implementation is defined by its class
• Objects are created by instantiating a class
• Class inheritance
• New classes can be defined in terms of existing
classes
• Abstract class
• Subclasses override parent operations
• Families of objects with related functionality
Class versus Interface Inheritance
• Class and type: are they different?
• Class
• defines how the object is implemented

• Type
• only refers to its interface
• object can have many types, and objects of different
classes can have the same type
• Class defines type
• (Sub) Class inheritance and (subtype) interface inheritance
• Design patterns depend on this distinction
• Chain of responsibility, composite, command, observer
Program to an Interface, not an Implementation
• Class inheritance or Interface inheritance?
• Interface inheritance defines subclasses as subtypes
• Benefits of interface inheritance
• Clients remain unaware of the specific types of objects they use
• Clients remain unaware of the classes that implement these
objects.
• Reduces implementation dependencies between subsystems
• Common themes for design patterns
• Don't declare variables to be instances of particular concrete
classes.
• Instead, commit only to an interface defined by an abstract class

• How to then instantiate concrete classes?


• Use creational design patterns
• factory design patterns
Putting Reuse Mechanisms to Work
• How to use basic OO concepts to build flexible,
reusable software?
• Inheritance
• Composition
• Delegation
• Parameterized classes
Inheritance versus Composition
• The two most common techniques for reusing
• Inheritance and Composition

• Class inheritance leads to White box reuse


• Object composition leads to Black box reuse
• Requires that the objects being composed have
well-defined interfaces.
• Class inheritance
• Pros: Static, Straightforward, Easy
• Cons: fixed, breaks encapsulation, not flexible
Inheritance versus Composition
• Object composition is defined dynamically at run-time
through objects acquiring references to other objects
• Don't break encapsulation
• Fewer implementation dependencies
• Keep each class encapsulated and focused on one task
• Classes and class hierarchies will remain small and will be
less likely to grow into unmanageable monsters.
• But, will have more objects

• Favor object composition over class inheritance.


Delegation
• Two objects are involved in handling a request: a receiving object
delegates operations to its delegate
• The receiver passes itself to the delegate to let the delegated
operation refer to the receiver.
• Ex. Window with rectangle
• Advantage
• Easy to compose behaviors at run-time and to change the way
they're composed.
• Disadvantage
• Dynamic, highly parameterized software is harder to understand
than more static software
• Run-time inefficiencies due to indirection

• Delegation is a good design choice only when it simplifies more than it


complicates.
• Patterns- state, strategy, visitor
• You can always replace inheritance with object composition as a
mechanism for code reuse
Designing for Change
• Maximize reuse
• anticipating
• new requirements
• changes to existing requirements

• Changes
• Class Redefinition and Reimplementation
• Client Modification
• Retesting

• Design patterns help you avoid these changes by


ensuring that a system can change in specific ways
Causes of Redesign
• Creating an object by specifying a class explicitly
• Dependence on specific operations
• Dependence on hardware and software platform
• Dependence on object representations or
implementations
• Algorithmic dependencies
• Tight coupling
• Extending functionality by subclassing
• Inability to alter classes conveniently
How not to Use design patterns
• Design patterns should not be applied
indiscriminately
• Often they achieve flexibility and variability by
introducing additional levels of indirection, and
that can complicate a design and/or cost you some
performance
• A design pattern should only be applied when the
flexibility it affords is actually needed
• The Consequences sections are most helpful when
evaluating a pattern's benefits and liabilities
Organizing design patterns
• Vary in granularity and level of abstraction
• Purpose
• Creational
• Factory Method
• Structural
• Adapter
• Behavioral
• State

• Scope
• Class
• object
Creational Patterns
• Concerned with the construction of instances of
classes
• Encapsulate knowledge about which concrete
classes the system uses
• Hide how instances of these classes are created
and put together
• Singleton, Factory Method, Abstract Factory,
Prototype, Builder
Factory Method- Example
//client code
{
Client Shape Shape l = new Line();
Shape p = new
draw() Polygon();
Shape c= new Circle();
}

Line Polygon Circle

draw() draw() draw()


Factory Method- Example

Client ShapeFactory Shape


Shape CreateShape()

//CreateShape code PolygonFactory Polygon Circle


{
return new Circle() Shape CreateShape()
}

//client code
CircleFactory
{
Shape CreateShape() ShapeFactory sf= new PolygonFactory();
Shape p = sf.CreateShape();
Shape c= new Circle();
}
Factory Method
• Intent: Define an interface for creating an object, but let
subclasses decide which class to instantiate.
• Let the class defer instantiation to subclasses.

• Motivation:
• Allow implementation of a framework that can create objects
without committing to the actual types of objects being created.
• The framework knows when to create objects, but it can’t anticipate
the class of objects it must create.

• Applicability
• a class can't anticipate the class of objects it must create.
• a class wants its subclasses to specify the objects it creates.
• classes delegate responsibility to one of several helper subclasses,
and you want to localize the knowledge of which helper subclass is
the delegate
Factory Method
Factory Method - Participants
•Product
•Concrete Product
•CreationRequestor
•FactoryIF
•Factory
Consequences
• Eliminate the need to bind application-specific
classes into your code
• A potential disadvantage
• clients might have to subclass the Creator class
just to create a particular ConcreteProduct
object
Known Uses & Related Patterns
• Toolkits, frameworks
• Related Patterns
• Abstract Factory, Template
Structural Patterns
• Address issues concerned with the way in which classes
and objects are organized.
• Offers effective ways of using object-oriented constructs
such as
• inheritance,
• composition and
• aggregation to satisfy particular requirements.
(some) Structural Patterns
Adapter
• Intent
• Convert the interface of a class into another interface
that clients expect
• Motivation:
• Sometimes you can’t reuse a class because the interface
doesn’t match what is required
• 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.
Motivating Example - Adapter

Object Adapter CircleTwo


Client Shape
draw()
myDraw()

myCircle
Line Polygon Circle

draw() draw() draw()

{ {
//code here myCircle.myDraw()
} }
Class Adapter

Uses Multiple Inheritance – Implementation of Adaptee and interface of Target


Object Adapter

Uses Delegation
Participants/Collaborations
• Target:
• Defines the domain specific interface used by the client

• Client:
• Collaborates with the objects conforming to the target.
• Calls on the Adapter instance.

• Adaptee:
• Defines an existing interface that needs adapting

• Adapter:
• Adapts the interface of the adaptee to the target
• Calls the adaptee’s operations to carry out the client
request.
Consequences
• Class adapter
• Subclass of adaptee cannot be adapted
• Adapter can override adaptee’s behavior
• Introduces only one object

• Object adapter
• single Adapter work with many
• harder to override Adaptee behavior.
Behavioural Patterns
• Concerned with algorithms and the assignment of
responsibilities between objects
• Describe not just patterns of objects or classes but
also the patterns of communication between
them
• Represent complex control flow that's difficult to
follow at run-time
• Focus away from flow of control to let you
concentrate just on the way objects are
interconnected
(Some) Behavioral patterns
Strategy Pattern- sorting numbers
Strategy pattern
• Intent
• Define a family of algorithms, encapsulate each
one, and make them interchangeable.
• Strategy lets the algorithm vary independently
from clients that use it.
• 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.
• To eliminate conditionals in a class
Consequences
• Families of related algorithms
• Strategies eliminate conditional statements
• A choice of implementations
• Clients must be aware of different Strategies
• Increased number of objects
Review
• What is a design pattern?
• What is the intent of adapter design pattern?
• What is the purpose of creational patterns?
• State the two most important design principles
that were discussed in this module.
Summary
• Designing (Reusable & Flexible) object oriented
software is hard
• Design patterns represent the “distilled”
knowledge from expert developers
• Principles of good OO design
• Program to an interface, not implementation
• Favor composition over class inheritance

• Patterns are systematically documented and


catalogued
• Look for patterns in other areas of development!
Reference
• Design Patterns: Elements of Reusable
Object-Oriented Software by Erich Gamma,
Richard Helm, Ralph Johnson, John Vlissides,
Addison-Wesley Pub Co;
• Hillside group: www.hillside.net

You might also like