Nothing Special   »   [go: up one dir, main page]

Design Patterns: Dr. Mani Sarma - Vittapu

Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

DESIGN PATTERNS

Dr. Mani Sarma.Vittapu

TEXT BOOKS:
1.Design Pattern by Erich Gamma, Pearson Education
2.Pattern’s in JAVA Vol-I BY Mark Grand, Wiley DreamTech
3.Pattern’s in JAVA Vol-II BY Mark Grand, Wiley DreamTech
4.JAVA Enterprise Design Patterns Vol-III Mark Grand, Wiley
Dream Tech
5.Head First Design Patterns By Eric Freeman-Oreilly-spd..
6.Design Patterns Explained By Alan Shalloway,Pearson Education
Overview of Design Patterns 1
1 What is Design Pattern?
2 Design Patterns in Smalltalk MVC
3 Describing Design Patterns
4 The catalog of Design Patterns
5 Organizing the catalog
6 How Design Patterns Solve Design Problems
7 How to select Design Patterns
8 How to Use a Design Pattern

Overview of Design Patterns 2


L1
What is a Design Pattern?
• Each pattern Describes a problem which occurs over and
over again in our environment ,and then describes the
core of the problem
• Novelists, playwrights and other writers rarely invent new
stories.
• Often ideas are reused, such as the “Tragic Hero” from
Hamlet or Macbeth.
• Designers reuse solutions also, preferably the “good” ones
– Experience is what makes one an ‘expert’
• Problems are addressed without rediscovering solutions
from scratch.
– “My wheel is rounder”

Overview of Design Patterns 3


L1

Design Patterns

Design Patterns are the best solutions for the


re-occurring problems in the application
programming environment.

• Nearly a universal standard


• Responsible for design pattern analysis in
other areas, including GUIs.
• Mainly used in Object Oriented programming

Overview of Design Patterns 4


Defining Design Patterns
• Design patterns are recurring solutions to design problems
you see over et. al., 1998).
Design patterns constitute a set of rules describing how to
accomplish certain tasks in the real of
softwaredevelopment.” (Pree, 1994)
“Design patterns focus more on reuse of recurring architectural
design themes, while frameworks focus on detailed design…
and implementation.” (Coplien & Schmidt, 1995).
“A pattern addresses a recurring design problem that arises in
specific design situations and presents a solution to it”
(Buschmann, et. al. 1996)
• “Patterns identify and specify abstractions that are above
the level of single classes and instances, or of components.”
(Gamma, et al., 1993)
Overview of Design Patterns 5
L1

Design Pattern Elements


1. Pattern Name
Handle used to describe the design
problem
Increases vocabulary
Eases (lack of difficulty in doing
something) design discussions
Evaluation without implementation
details
Overview of Design Patterns 6
L1

Design Pattern Elements


2. Problem
Describes when to apply a pattern
May include conditions for the pattern to
be applicable
Symptoms of an inflexible design or
limitation

Overview of Design Patterns 7


L1

Design Pattern Elements


3. Solution
Describes elements for the design
Includes relationships, responsibilities,
and collaborations
Does not describe concrete designs or
implementations
A pattern is more of a template

Overview of Design Patterns 8


L1

Design Pattern Elements


4. Consequences
Results and Trade Offs
Critical for design pattern evaluation
Often space and time trade offs
Language strengths and limitations
(Broken into benefits and drawbacks for
this discussion)

Overview of Design Patterns 9


L1

Design patterns can be subjective.


One person’s pattern may be another
person’s primitive building block.

The focus of the selected design patterns


are:
Object and class communication
Customized to solve a general design
problem
Solution is context specific
Overview of Design Patterns 10
L2

Design patterns in Smalltalk MVC


 The Model/View/Controller triad of classes is
used to build user interfaces in Smalltalk-80

 MVC consists of three kinds of objects.


 M->>MODEL is the Application object.
 V->>View is the screen presentation.
 C->>Controller is the way the user interface reacts to
user input.

MVC decouples to increase flexibility and reuse.


Overview of Design Patterns 11
L2

Design patterns in Smalltalk MVC

• MVC decouples views and models by


establishing a subscribe/notify protocol between
them.
A view must ensure that its appearance must
reflects the state of the model.
Whenever the model’s data changes, the model
notifies views that depends on it.
You can also create new views for a model without
Rewriting it.

Overview of Design Patterns 12


L2

Design Patterns in
smalltalkMVC
 The below diagram shows a model and three views.
 The model contains some data values, and the views
defining a spreadsheet, histogram, and pie chart
display these data in various ways.
 The model communicates with it’s values change,
and the views communicate with the model to access
these values.
 Feature of MVC is that views can be nested.
Easy to maintain and enhancement.
Overview of Design Patterns 13
L2

Design Patterns in
smalltalkMVC
Relative Percentages
A B C D
A
X 15 35 35 15 D
Y 10 40 30 20 B
C
Z 10 40 30 20
A B C D

A=10%
B=40%
C=30% Application data
Change notification
D=20%
Requests, modifications
Overview of Design Patterns 14
L3

Describing Design Patterns :

 Graphical notations ,while important and


useful, aren’t sufficient.
 They capture the end product of the design
process as relationships between classes
and objects.
 By using a consistent format we describe
the design pattern .
 Each pattern is divided into sections
according to the following template.

Overview of Design Patterns 15


L3
Describing Design Patterns
Pattern Name and Classification:
 it conveys the essence of the pattern succinctly (briefly,
concisely) good name is vital, because it will become
part of design vocabulary.
• 7 Basic patterns, 5 Creational patterns, 4 Collection patterns,
• 11 Structural patterns, 11 Behavioral patterns, 4 Concurrency patterns
Intent (aim,goal,target): What does the design pattern do?
 What is it’s rational and intend?
 What particular design issue or problem does it
address?
Also Known As: Other well-known names for the pattern, if
any.
Motivation: A scenario that illustrates a design problem
and how the class and object structures in the pattern
solve the problem.
 The scenario will help understand the more abstract
description of the pattern that follows.
Overview of Design Patterns 16
L3

Describing Design Patterns


Applicability:
• Applicability: What are the situations in which the design patterns
can be applied?
• What are example of the poor designs that the pattern can
address?
• How can recognize situations?
• Structure: Graphical representation of the classes in the pattern
using a notation based on the object Modeling Technique(OMT).
• Participants: The classes and/or objects participating in the
design pattern and their responsibilities.
Structure:
 Graphical representation of the classes in the pattern using a
notation based on the object Modeling Technique(OMT).

Participants:
The classes and/or objects participating in the design

pattern and their responsibilities.
Overview of Design Patterns 17
L3

Describing Design Patterns


Collaborations:
 How the participants collaborate to carry out their
responsibilities.
Consequences:
 How does the pattern support its objectives?
 What are the trade-offs and result of using the pattern ?
 What aspect of the system structure does it let vary
independently?
Implementation:
 What pitfalls,hints,or techniques should be aware of when
implementing the pattern ?
 Are there language-specific issues?

Overview of Design Patterns 18


L3

Describing Design Patterns


Sample Code:
 Code fragments that illustrate how might implement the
pattern in c++ / Smalltalk / Java / C#.
Known Uses:
Examples of the pattern found in real systems.
Related Patterns:
What design patterns are closely related to this one?
What are the Major differences?
With Which other patterns should this one be used?

Overview of Design Patterns 19


Describing the Summary of DP
• Pattern Name and Classification: A descriptive and unique name that helps in identifying and
referring to the pattern.
• Intent: A description of the goal behind the pattern and the reason for using it.
• Also Known As: Other names for the pattern.
• Motivation (Forces): A scenario consisting of a problem and a context in which this pattern
can be used.
• Applicability: Situations in which this pattern is usable; the context for the pattern.
• Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams
may be used for this purpose.
• Participants: A listing of the classes and objects used in the pattern and their roles in the
design.
• Collaboration: A description of how classes and objects used in the pattern interact with each
other.
• Consequences: A description of the results, side effects, and trade offs caused by using the
pattern.
• Implementation: A description of an implementation of the pattern; the solution part of the
pattern.
• Sample Code: An illustration of how the pattern can be used in a programming language.
• Known Uses: Examples of real usages of the pattern.
Related Patterns: Other patterns that have some relationship with the pattern; discussion of

the differences between the pattern and similar patterns .


Overview of Design Patterns 20
L4

The Catalog of Design Pattern


Abstract Factory: Provide an interface for creating
families of related or dependent objects without
specifying their concrete classes. Ex: Multiple
window Systems, classes,scrollbars, Buttons,
menus etc..
Adaptor: Convert the interface of a class into another
interface clients expect. Ex. A drawing Editors into
pictures and diagrmas like Lines, polygon,text,etc..
Bridge: Decouple an abstraction from its implemen-
tation so that two can vary independently.
Ex. Xwindows and IBM presentation Manager (PM)

Overview of Design Patterns 21


Abstract ,Adapter & Bridge
• The Abstract Parent Class pattern is useful for designing a framework
for the consistent implementation of functionality common to a set of
related classes.
• An abstract method is a method that is declared, but contains no
implementation. An abstract class is a class with one or more abstract
methods. Abstract methods, with more than one possible
implementation, represent variable parts of the behavior of an abstract
class. An abstract class may contain implementations for other methods,
which represent the invariable parts of the class functionality.
• Adapter: Allows the conversion of the interface of a class to another
interface that clients expect. This allows classes with incompatible
interfaces to work together.
• Builder: Allows the creation of a complex object by providing the
information on only its type and content, keeping the details of the object
creation transparent to the client. This allows the same construction
process to produce different representations of the object.
Overview of Design Patterns 22
L4
The Catalog of Design Pattern
• Builder: Separates the construction of the complex object
from its representation so that the same constriction
process can create different representations.
A reader for the RTF (Rich Text Format) document exchange
format should be able to convert RTF to many text
formats. Ex. an ASCIIConverter, A TextWidgetConverter.
• Chain of Responsibility: Avoid coupling the sender of a
request to it’s 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 objects
handles it. For example, a button widget in a dialog box
might have different help information than a similar button
in the main window. Save,OK,apllication,print buttons
etc…

• Overview of Design Patterns 23


Builder &Chain of Responsibility
Builder: Allows the creation of a complex object by
providing the information on only its type and
content, keeping the details of the object creation
transparent to the client. This allows the same
construction process to produce different
representations of the object.

Chain of Responsibility :Avoids coupling a (request)


sender object to a receiver object. Allows a sender
object to pass its request along a chain of objects
without knowing which object will actually handle the
request.
Overview of Design Patterns 24
L4
The Catalog of Design Pattern
• Command: Encapsulate a request as an object ,thereby
letting parameterize clients with different request, queue or
log requests, and support undoable operations.For example,
user interface toolkits include objects like buttons and menus
that carry out a request in response to user input.
• Composite: Compose objects into tree objects to represent
part-whole hierarchies. Composite lets clients treat individual
objects and compositions of objects uniformly.Graphics
applications like drawing editors and schematic capture
systems let users build complex diagrams out of simple
components. The user can group components to form larger
components, which in turn can be grouped to form still larger
components. Classes for graphical primitives such as text and
lines plus other classes that acts as containers for these
primitives.
• Ex. implements a graphic class, which can be either an ellipse
or a composition of several graphics. Every graphic can be
printed. Overview of Design Patterns 25
L4
The Catalog of Design Pattern
• Decorator: Attach additional responsibilities to an object
dynamically. Decorators provide a flexible alternative to sub
classing for extending functionality. For example, suppose we
have a TextView object that displays text in a window. TextView
has no scroll bars by default, because we might not always
need them. When we do, we can use a Scroll Decorator to add
them. Suppose we also want to add a thick black border
around the TextView. We can use a Border Decorator to add
this as well. We simply compose the decorators with the
TextView to produce the desired result.
• Façade: Provide a unified interface to a set of interfaces in a
subsystem's Facade defines a higher-level interface that
makes the subsystem easier to use. Ex. a programming
environment that gives applications access to its compiler
subsystem.This subsystem contains classes such as scanner,
Parser, ProgramNode, BytecodeStream, and Program
Overview of Design Patterns 26
nodeBuilder that implement the compiler.
L4
The Catalog of Design Pattern
• Factory Method: Defines an interface for creating an object ,but let
subclasses decide which class to instantiate. Factory Method lets a class
defer instantiation to subclasses.
• To create a drawing application, for example, we define the classes
DrawingApplication and DrawingDocument.The Application class is
responsible for managing Documents and will create them as required
when the user selects Open or New from a menu.
• Flyweight: Use sharing to support large numbers of fine-grained objects
efficiently. For example, most document editor implementations have text
formatting and editing facilities that are modularized to some extent. Object-
oriented document editors typically use objects to represent embedded
elements like tables and figures.
• Interpreter: Given a language, defining a representation of its grammar
along with an interpreter that uses the representation to interpret sentences
in the language. The Interpreter pattern describes how to define a grammar
for simple languages, represent sentences in the language, and interpret
the sesentences. In this example, the pattern describes how to define a
grammar for regular expressions, represent a particular regular expression,
and how to interpret that regular expression.
For example, searching for strings that match a pattern is a common problem.

Overview of Design Patterns 27
L4
The Catalog of Design Pattern
• Iterator:Provide a way to access the element of an
aggregate object sequentially without exposing its
underlying representation.
• For example, a List class would call for a List Iterator
with the following relationship between them
• Mediator:Define an object that encapsulate how a set
of objects interact. Mediator promotes loose coupling
by keeping objects from referring to each other
explicitly, and let’s you very their interaction
independently.Ex. consider the implementation of
dialog boxes in a graphical user interface. A dialog box
uses a window to present a collection of widgets such
as buttons, menus,Overview
and entry fields etc..
of Design Patterns 28
The Catalog of Design Pattern
• Memento: Without violating encapsulation, capture and
externalize an object’s internal state so that object can be
restored to this state later. Consider for example a graphical
editor that supports connectivity between objects. A user can
connect two rectangles with a line, and the rectangles stay
connected when the user moves either of them. The editor
ensures that the line stretches to maintain the connection.
• Observer: Define a one-to-many dependency between objects
so that when one object changes state, all it’s dependents are
notified and updated automatically. For example, many
graphical user interface toolkits separate the presentational
aspects of the user interface from the underlying application
data. Classes defining application data and presentations can
be reused independently. They can work together, too. Both a
spreadsheet object and bar chart object can depict information
in the same application data object using different
presentations..
Overview of Design Patterns 29
L4
The Catalog of Design Pattern
• Prototype:Specify the kinds of objects to create using a
prototypical instance, and create new objects by copying this
prototype. Ex. music editor, each tool for creating a music
object is an instance of Graphic Tool that's initialized with a
different prototype.
• Proxy: Provide a surrogate or placeholder for another object
to control access to it. But opening a document should be
fast, so we should avoid creating all the expensive objects at
once when the document is opened. Ex.IS,DS,App.Servers
• Singleton: Ensure a class has only one instance, and provide
a point of access to it. Ex. Maths Class
• State: Allow an object to alter its behavior when its internal
state changes. the object will appear to change its class.
• Ex. TCP connection Object states:Established,listining,closed
Overview of Design Patterns 30
The Catalog of Design Pattern
• Strategy: Define a family of algorithms, encapsulate each one,
and make them interchangeable. Strategy lets the algorithm vary
independently from clients that use it.
• Template Method: Define the Skelton of an operation, deferring
some steps to subclasses. Template method subclasses redefine
certain steps of an algorithm without changing the algorithms
structure.
• Visitor: 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.

Overview of Design Patterns 31



Summary of Catalog of design patterns

• Creational Patterns
• Abstract Factory Creates an instance of several
families of classes
• Builder Separates object construction from its
representation
• Factory Method Creates an instance of several
derived classes
• Prototype A fully initialized instance to be copied
or cloned
• Singleton A class of which only a single instance
can exist
Overview of Design Patterns 32
Summary of Catalog of design patterns
• Structural Patterns
• Adapter Match interfaces of different classes
• Bridge Separates an object’s interface from its
implementation
• Composite A tree structure of simple and composite
objects
• Decorator Add responsibilities to objects dynamically
• Facade A single class that represents an entire
subsystem
• Flyweight A fine-grained instance used for efficient
sharing
• Proxy An object representing another object

Overview of Design Patterns 33


Summary of Catalog of design patterns
• Behavioral Patterns
• Chain of Resp. A way of passing a request between a chain of
objects
• Command Encapsulate a command request as an object
• Interpreter A way to include language elements in a program
• Iterator Sequentially access the elements of a collection
• Mediator Defines simplified communication between classes
• Memento Capture and restore an object's internal state
• Observer A way of notifying change to a number of classes
• State Alter an object's behavior when its state changes
• Strategy Encapsulates an algorithm inside a class
• Template Method Defer the exact steps of an algorithm to a
subclass
• Visitor Defines a new operation to a class without change
Overview of Design Patterns 34
L5

Organizing the Catalog


Two criteria
Purpose: what a pattern does
Creational: concern the process of object
creation
Structural: the composition of classes or
objects
Behavioral: characterize the ways in which
classes or objects interact and distribute
responsibility
Scope: whether the pattern applies primarily to
classes or to objects
Overview of Design Patterns 35
Organizing the Catalog

• Design patterns vary in their granularity and level


of abstraction.
• As there are many design patterns, we can
organize or classify patterns to learn them faster.
• Here we classify the patterns along two
dimensions:
• One is purpose which reflects what a pattern does
and
• The second one is scope which specifies whether
the pattern applies to classes or objects.

Overview of Design Patterns 36


Creational Patterns
• creational design patterns are design patterns that deal with
object creation mechanisms, trying to create objects in a manner
suitable to the situation. 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.
• Creational design patterns are composed of two dominant ideas. One is
encapsulating knowledge about which concrete classes the system
use. Another is hiding how instances of these concrete classes are
created and combined.
• Creational design patterns are further categorized into Object
creational patterns and Class-creational patterns.
• Object-creational patterns deal with Object creation
• Class creational patterns deal with Class-instantiation .
• Object-creational patterns defer part of its object creation to another
object, while Class-creational patterns defer its objection creation to
subclasses.
Overview of Design Patterns 37
Structural Patterns
• S P are concerned with how classes and objects are
composed to form larger structures.
• SCP use inheritance to compose interface or
implementations.
• Ex. How multiple inheritance mixes two or more classes
into one. The result is a class that combines the
properties of its parent classes. Adapter makes one
interface (Adaptee) conform to another. Therefore
providing a uniform abstraction of different interfaces.
• SOP describes a ways to compose objects
to realize new functionalities.

Overview of Design Patterns Describes a ways t38


Behavioral Patterns
• BP are concerned with algorithms and the assignment of
responsibilities between objects.
• BP are described not just patterns of objects or classes
but also the patterns of communication between objects
and classes.
• BCP use inheritance of distribute behavioral between
classes
• BOP use object composition rather than inheritanc
Ex. Peer objects nodes known about each other . Peer
could maintain explicit references to each other, but that
increases their coupling.
Every object would know about every object nodes.

Overview of Design Patterns 39


Overview of Design Patterns 40
L6

How Design Patterns Solve


Design Problems
• Finding Appropriate Objects
– Decomposing a system into objects is the hard part
– OO-designs often end up with classes with no
counterparts in real world (low-level classes like
arrays)
– Strict modeling of the real world leads to a system
that reflects today’s realities but not necessarily
tomorrows
– Design patterns identify less-obvious abstractions

Overview of Design Patterns 41


L6

How Design Patterns Solve


Design Problems
• Determining Object Granularity
– Objects can vary tremendously in size and
number
– Facade pattern describes how to represent
subsystems as objects
– Flyweight pattern describes how to support
huge numbers of objects

Overview of Design Patterns 42


L6
Design Pattern relationship
• Mapping
Memento
Proxy
saving state
Adapter
of iteration
Builder Avo
Iterator hys iding Bridge
cre tere
a sis
com ting
s po si Enumerating
te
children
composed Command
Composite
using
adding
respnsibilities sharing def
Decorator de in
to objects ad the ing
composites op ding tra fini ch a
era ve ng in
ti o rs
n a ls
changing skin s
defining Chain of
versus guts Flyweight
grammar Responsibility
sh Visitor
ter aring in g
ing
shar gies sy min add ations
r
strat
e sharing mb al Interpreter ope
Strategy ols
strategies complex
Mediator dependency Observer
State management
con defining
fi
Prototype dyn gure fa algorithm´s often uses
ami c Template Method
cally tory steps Factory Method

t
single Abstract Factory implemen
instance using
Singleton single Facade
instance
Overview of Design Patterns 43
L6

Specifying Object Interfaces


• Interface:
– Set of all signatures defined by an object’s operations
– Any request matching a signature in the objects interface may be sent
to the object
– Interfaces may contain other interfaces as subsets
• Type:
– Denotes a particular interfaces
– An object may have many types
– Widely different object may share a type
– Objects of the same type need only share parts of their interfaces
– A subtype contains the interface of its super type
• Dynamic binding, polymorphism

Overview of Design Patterns 44


L6

Specifying Object Implementations


• An object’s implementation is defined by its class
• The class specifies the object’s internal data and
defines the operations the object can perform
• Objects is created by instantiating a class
– an object = an instance of a class
• Class inheritance
– parent class and subclass

Overview of Design Patterns 45


L6

Specifying Object Implementations


(cont.)
• Abstract class versus concrete class
– abstract operations
• Override an operation
• Class versus type
– An object’s class defines how the object is
implemented
– An object’s type only refers to its interface
– An object can have many types, and objects of
different classes can have the same type
Overview of Design Patterns 46
L6

Specifying Object Implementations


(cont.)
• Class versus Interface Inheritance
– class inheritance defines an object’s
implementation in terms of another object’s
implementation (code and representation sharing)
– interface inheritance (or subtyping) describes
when an object can be used in place of another
• Many of the design patterns depend on this
distinction

Overview of Design Patterns 47


L6

Specifying Object Implementations


(cont.)
• Programming to an Interface, not an
Implementation
• Benefits
– clients remain unaware of the specific
types of objects they use
– clients remain unaware of the classes that
implement these objects

Overview of Design Patterns 48


L6

Program to an interface,
not an implementation
• Manipulate objects solely in terms of interfaces
defined by abstract classes!

• Benefits:
1. Clients remain unaware of the specific types of objects they use.
2. Clients remain unaware of the classes that implement the objects.
Clients only know about abstract class(es) defining the interfaces

• Do not declare variables to be instances of particular concrete classes


• Use creational patterns to create actual objects.

Overview of Design Patterns 49


L6

Favor object composition


over class inheritance
• White-box reuse:
– Reuse by subclassing (class inheritance)
– Internals of parent classes are often visible to subclasses
– works statically, compile-time approach
– Inheritance breaks encapsulation
• Black-box reuse:
– Reuse by object composition
– Requires objects to have well-defined interfaces
– No internal details of objects are visible

Overview of Design Patterns 50


L6

Putting Reuse Mechanisms to Work


• Inheritance versus Composition
• Delegation
• Inheritance versus Parameterized
Types

Overview of Design Patterns 51


L6

Inheritance versus Composition


• Two most common techniques for reuse
– class inheritance
• white-box reuse
– object composition
• black-box reuse
• Class inheritance
– advantages
• static, straightforward to use
• make the implementations being reuse more easily

Overview of Design Patterns 52


L6

Inheritance versus Composition (cont.)


• Class inheritance (cont.)
– disadvantages
• the implementations inherited can’t be changed
at run time
• parent classes often define at least part of their
subclasses’ physical representation
– breaks encapsulation
• implementation dependencies can cause
problems when you’re trying to reuse a
subclass

Overview of Design Patterns 53


L6

Inheritance versus Composition (cont.)


• Object composition
– dynamic at run time
– composition requires objects to respect ea
ch others‘ interfaces
• but does not break encapsulation
– any object can be replaced at run time
– Favoring object composition over class inh
eritance helps you keep each class encaps
ulated and focused on one task
Overview of Design Patterns 54
L6

Inheritance versus Composition (cont.)


• Object composition (cont.)
– class and class hierarchies will remain small
– but will have more objects
• Favor object composition over class
inheritance
• Inheritance and object composition
should work together

Overview of Design Patterns 55


L6

Delegation
• Two objects are involved in handling a
request: a receiving object delegates
operations to its delegate
Window Rectangle
rectangle
Area() Area()
width
height

Overview of Design Patterns 56


L6

Delegation (cont.)
• Makes it 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
• Delegation is a good design choice only when it
simplifies more than it complicates
• Delegation is an extreme example of object
composition
Overview of Design Patterns 57
L6

Inheritance versus Parameterized


Types
• Let you define a type without specifying all
the other types it uses, the unspecified types
are supplied as parameters at the point of use
• Parameterized types, generics, or templates
• Parameterized types give us a third way to
compose behavior in object-oriented systems

Overview of Design Patterns 58


L6

Inheritance versus Parameterized


Types (cont.)
• Three ways to compose
– object composition lets you change the behavior
being composed at run-time, but it requires
indirection and can be less efficient
– inheritance lets you provide default
implementations for operations and lets
subclasses override them
– parameterized types let you change the types
that a class can use

Overview of Design Patterns 59


L6

Relating Run-Time and Compile-Time


Structures
• An object-oriented program’s run-time structure
often bears little resemblance to its code
structure
• The code structure is frozen at compile-time
• A program’s run-time structure consists of rapidly
changing networks of communicating objects
• aggregation versus acquaintance (association)
– part-of versus knows of

Overview of Design Patterns 60


L6

Relating Run-Time and Compile-Time


Structures (cont.)
• The distinction between acquaintance
and aggregation is determined more by
intent than by explicit language
mechanisms
• The system’s run-time structure must
be imposed more by the designer than
the language

Overview of Design Patterns 61


L6

Designing for Change


• A design that doesn’t take change into
account risks major redesign in the
future
• Design patterns help you avoid this by
ensuring that a system can change in
specific ways
– each design pattern lets some aspect of
system structure vary independently of
other aspects
Overview of Design Patterns 62
L6

Common 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
Overview of Design Patterns 63
L6

Common Causes of Redesign (cont.)


• Tight coupling
• Extending functionality by subclassing
• Inability to alter classes conveniently

Overview of Design Patterns 64


L6

Design for Change (cont.)


• Design patterns in application programs
– Design patterns that reduce dependencies
can increase internal reuse
– Design patterns also make an application
more maintainable when they’re used to
limit platform dependencies and to layer a
system

Overview of Design Patterns 65


L6

Design for Change (cont.)


• Design patterns in toolkits
– A toolkit is a set of related and reusable
classes designed to provide useful,
general-purpose functionality
– Toolkits emphasize code reuse. They are
the object-oriented equivalent of subroutine
libraries
– Toolkit design is arguably harder than
application design
Overview of Design Patterns 66
L6

Design for Change (cont.)


• Design patterns in framework
– A framework is a set of cooperating classes that
make up a reusable design for a specific class of
software
– You customize a framework to a particular
application by creating application-specific
subclasses of abstract classes from the framework
– The framework dictates the architecture of your
application

Overview of Design Patterns 67


L6

Design for Change (cont.)


• Design patterns in framework (cont.)
– Frameworks emphasize design reuse over code
reuse
– When you use a toolkit, you write the main body of
the application and call the code you want to
reuse. When you use a framework, you reuse the
main body and write the code it calls.
– Advantages: build an application faster, easier to
maintain, and more consistent to their users

Overview of Design Patterns 68


L6

Design for Change (cont.)


• Design patterns in framework (cont.)
– Mature frameworks usually incorporate several
design patterns
– People who know the patterns gain insight into the
framework faster
– differences between framework and design pattern
• design patterns are more abstract than frameworks
• design patterns are smaller architectural elements than
frameworks
• design patterns are less specialized than frameworks

Overview of Design Patterns 69


L7

How To Select a Design Pattern


 Consider how design patterns solve
design problems.
 Scan Intent sections.
 Study how patterns interrelate.
 Study patterns of like purpose.
 Examine a Cause of redesign.
 Consider what should be variable in your
design.

Overview of Design Patterns 70


L7

Design Pattern Relationship

Overview of Design Patterns 71


L8

How To Use a Design Pattern

 Read the pattern once through for an overview.


 Go Back and study the Structure, Participants ,and
Collaborations sections.
 Look At the Sample Code section to see a concrete
Example of the pattern in code.
Choose names for pattern participants that are
meaningful in the application context.
Define the classes.
Overview of Design Patterns 72
L8

Design Aspects that


design patterns let
you vary

Overview of Design Patterns 73


L9

Online resources
• Pattern FAQ
• http://g.oswego.edu/dl/pd-FAQ/pd-FAQ.html

• Basic patterns
• http://exciton.cs.oberlin.edu/javaresources/Desi
gnPatterns/default.htm
• Patterns home page
• http://hillside.net/patterns/

Overview of Design Patterns 74

You might also like