design patterns

53
February 28, 2009 Design Pattern Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd. Abstractions in OOD Current Practices in Object Oriented Software Development Meghnad Saha Institute of Technology

Upload: ppd1961

Post on 28-Jan-2015

2.402 views

Category:

Technology


0 download

DESCRIPTION

This is a part of my series of presentations on C++ and Design Pattern. This is still being developed.

TRANSCRIPT

Page 1: Design Patterns

February 28, 2009

Design Pattern

Dr. Partha Pratim DasInterra Systems (India) Pvt. Ltd.

Abstractions in OOD

Current Practices in Object Oriented Software Development

Meghnad Saha Institute of Technology

Page 2: Design Patterns

28-Feb-09 2

Agenda

• Design Patterns – Patterns Everywhere– Fundamentals– Sample Pattern Overview

Page 3: Design Patterns

28-Feb-09 3

Pattern’s Everywhere

Quest in Human EndeavorQuest in Human Endeavor

Page 4: Design Patterns

28-Feb-09 4

Pattern’s Everywhere in Life

• Summer, Winter, Autumn, Spring: –Climatic Pattern

• New Moon, Full Moon: –Lunar Pattern

• Iron Filings in a Magnetic Fields: –Magnetic Pattern

• Patterns in Nature

Page 5: Design Patterns

28-Feb-09 5

Pattern’s Everywhere in Life• Bhairavi, Malkosh, Hansadhwani:

– Musical Pattern• Sonnet:

– Poetic Pattern• Bibi #1, Hero #1, Jodi #1, Premi #1:

– Bollywood Pattern• Heshtoric Win, The Damned, Grave end to Mutiny:

– Media Pattern• Simple, Complex, Compound Sentences:

– Grammatical Pattern• Patterns in Art / Humanities

Page 6: Design Patterns

28-Feb-09 6

Pattern’s Everywhere in Life

• 4-3-3, 5-2-3, 10: – Soccer Pattern

• Castling: – Chess Pattern

• Patterns in Sport

Page 7: Design Patterns

28-Feb-09 7

Pattern’s Everywhere in Life• BTK, Stone Man:

– Serial Killer Pattern• 9/11, 7/11, 26/11:

– Terror Pattern • Mughal, Gandhi:

– Dynastic Pattern• Patterns in Crime / Politics

Page 8: Design Patterns

28-Feb-09 8

Pattern’s Everywhere in Life• Baluchari, Benarasi, Pachhampalli:

– Silk Pattern• Palace, House, Apartment, Condo:

– Housing Pattern• Recipe:

– Cooking Pattern• Times New Roman, Arial, Verdana, Tahoma:

– Typesetting Pattern• Patterns in Construction

Page 9: Design Patterns

28-Feb-09 9

Pattern’s Everywhere in Life• Jiang Qing, Zhang Chunqiao, Yao Wenyuan, Wang

Hongwen– Cultural-Revolution excesses exposed on Mao's death

• Wang Dongxing, Wu De, Ji Dengkui, Chen Xilian– Hua Guofeng's clique; Crushed in 1980 by Deng Xiaoping

– Corrupt Collusion Pattern• Erich Gamma, Richard Helm, Ralph Johnson, John

Vlissides– GoF Book on Pattern

– Creative Consortium Pattern• Patterns in Collaboration

Page 10: Design Patterns

28-Feb-09 10

Pattern’s Everywhere in Life• Semi-Group, Monoid, Group, Abelian Group:

– Algebraic Pattern• Unconditional Branch, Conditional Branch, Definite

Loop, Indefinite Loop, Recursion:

– Programming Pattern• Divide-and-Conquer, Greedy, Dynamic

Programming, Branch-and-Bound:

– Algorithmic Pattern• Factory, Iterator, Visitor, Singleton:

– Design Pattern • Patterns in Computation

Page 11: Design Patterns

28-Feb-09 11

Pattern Pioneers

Kurt GodelKurt Godel (1906-1978) (1906-1978)

Austrian-American LogicianAustrian-American Logician

Who is he?This sentence is false

Page 12: Design Patterns

28-Feb-09 12

Who is he?

Pattern Pioneers

Champion of Graphic Patterns

Page 13: Design Patterns

28-Feb-09 13

Pattern Pioneers

Maurits Cornelis EscherMaurits Cornelis Escher (1898-1972) (1898-1972)

Dutch Graphic ArtistDutch Graphic Artist

Page 14: Design Patterns

28-Feb-09 14

Pattern Pioneers

Johann Sebastian BachJohann Sebastian Bach (1685-1750) (1685-1750)

German Composer & OrganistGerman Composer & Organist

Who is he?

Page 15: Design Patterns

28-Feb-09 15

Pattern Pioneers

Robert James FisherRobert James Fisher (1943-2008) (1943-2008)

US Chess World ChampUS Chess World Champ

Who is he?

Page 16: Design Patterns

28-Feb-09 16

Pattern Pioneers

Who is he?

Donald Ervin KnuthDonald Ervin Knuth (1938-) (1938-)

Father of Analysis of AlgorithmsFather of Analysis of Algorithms

Page 17: Design Patterns

28-Feb-09 17

There is one timeless way of building. It is a thousand years old, and the same today as it has ever been. The great traditional buildings of the past, the villages and tents and temples in which man feels at home, have always been made by people who were very close to the center of this way. It is not possible to make great buildings, or great towns, beautiful places, places where you feel yourself, places where you feel alive, except by following this way. And, as you will see, this way will lead anyone who looks for it to buildings which are themselves as ancient in their form, as the trees and hills, and as our faces are.

Pattern Pioneers

Who is he?Christopher AlexanderChristopher Alexander

(1936-) (1936-) Architect – The Pattern LanguageArchitect – The Pattern Language

Page 18: Design Patterns

28-Feb-09 18

Patterns in Life: Take Back

• Patterns Pervade

• Patterns Drive Research

• Patterns are the greatest exploits for Design

Page 19: Design Patterns

28-Feb-09 19

Design Patterns

Search of Similarities in OODSearch of Similarities in OOD

Page 20: Design Patterns

28-Feb-09 20

What is a Design Pattern?

• A Design Pattern – describes a problem

• Occurring over and over again (in software engineering)

– describes the solution • Sufficiently generic

• Applicable in a wide variety of contexts.

Recurring Solution to a Recurring ProblemRecurring Solution to a Recurring Problem

Page 21: Design Patterns

28-Feb-09 21

Essential Elements of a Design Pattern

1. Pattern Name: Descriptor for a design problem, its solutions, and their consequences.

2. Problem: Where to apply the pattern and its associated context.

3. Solution: Elements that make up the design, their relationships, responsibilities, and collaborations.

4. Consequences: Results and trade-offs in applying the pattern.

Page 22: Design Patterns

28-Feb-09 22

Example Pattern• Pattern Name

– Iterator• Problem

– How to serve Patients at a Doctor’s Clinic• Solution

– Front-desk manages the order for patients to be called• By Appointment• By Order of Arrival• By Extending Gratitude• By Exception• …

• Consequences– Patient Satisfaction– Clinic’s Efficiency– Doctor’s Productivity

Page 23: Design Patterns

28-Feb-09 23

Describing a Design Pattern

• Pattern Name and Classification– The pattern's name conveys the essence of the

pattern succinctly. • Intent

– A short statement on:• What does the design pattern do? • What is its rationale and intent? • What particular design issue or problem does it

address?

• Also Known As– Other well-known names for the pattern.

Page 24: Design Patterns

28-Feb-09 24

Describing a Design Pattern

• Motivation– A scenario that illustrates a design problem

and how the class and object structures in the pattern solve the problem.

• Applicability– What are the situations in which the design

pattern can be applied? – What are examples of poor designs that the

pattern can address? – How can you recognize these situations?

Page 25: Design Patterns

28-Feb-09 25

Describing a Design Pattern

• Structure– A graphical representation of the classes in

the pattern using a notation based on the Object Modeling Technique (OMT) – specifically UML.

• Participants– The classes and/or objects participating in the

design pattern and their responsibilities.• Collaborations

– How the participants collaborate to carry out their responsibilities?

Page 26: Design Patterns

28-Feb-09 26

Describing a Design Pattern

• Consequences– How does the pattern support its objectives? – What are the trade-offs and results of using

the pattern?– What aspect of system structure does can be

varied independently?• Implementation

– What pitfalls, hints, or techniques should you be aware of when implementing the pattern?

– Are there language-specific issues?

Page 27: Design Patterns

28-Feb-09 27

Describing a Design Pattern

• Sample Code– Code fragments to implement the pattern in

specific language (C++ or C# or Java).• Known Uses

– Examples of the pattern found in real systems. • Related Patterns

– What design patterns are closely related to this one?

– What are the important differences? – With which other patterns should this one be

used?

Page 28: Design Patterns

28-Feb-09 28

Iterator Pattern

• Pattern Name and Classification: – Iterator– Behavioral

• Intent– Provide a way to access – the elements – of an aggregate object (container) – sequentially – without exposing its underlying representation.

CONTAINERS•Array•Vector•List•Stack•Queue•Tree

SEQUENTIAL•Forward•Backward•Bidirectional•Random

ACCESS•Read•Write•Read-Write

Page 29: Design Patterns

28-Feb-09 29

Iterator Pattern

• Also Known As– Cursor

• Motivation– An aggregate object (list) should have a way to access

its elements without exposing its internal structure. – There is a need to traverse the list in different ways,

depending on a specific task. – Multiple traversals may be pending on the same list.– The key idea in this pattern is to take the responsibility

for access and traversal out of the list object and put it into an iterator object.

Page 30: Design Patterns

28-Feb-09 30

Iterator Pattern

• Motivation

Page 31: Design Patterns

28-Feb-09 31

Iterator Pattern

• Motivation

Page 32: Design Patterns

28-Feb-09 32

Iterator Pattern

• Applicability– to access an aggregate object's contents without

exposing its internal representation.– to support multiple traversals of aggregate

objects.– to provide a uniform interface for traversing

different aggregate structures (that is, to support polymorphic iteration).

Page 33: Design Patterns

28-Feb-09 33

Iterator Pattern

• Structure

Page 34: Design Patterns

28-Feb-09 34

Iterator Pattern

• Participants– Iterator

• defines an interface for accessing and traversing elements.

– ConcreteIterator• implements the Iterator interface.• keeps track of the current position in the traversal of the

aggregate.

– Aggregate• defines an interface for creating an Iterator object.

– ConcreteAggregate• implements the Iterator creation interface to return an instance

of the proper ConcreteIterator.

Page 35: Design Patterns

28-Feb-09 35

Iterator Pattern

• Collaborations– A ConcreteIterator keeps track of the current

object in the aggregate and can compute the succeeding object in the traversal.

• Consequences– It supports variations in the traversal of an

aggregate. – Iterators simplify the Aggregate interface. – More than one traversal can be pending on an

aggregate.

Page 36: Design Patterns

28-Feb-09 36

Iterator Pattern• Implementation

– Who controls the iteration?• External Iteration• Internal Iteration

– Who defines the traversal algorithm?– How robust is the iterator?

• What happens if items are inserted / deleted?– Additional Iterator operations– Using polymorphic iterators in C++.

• allocated dynamically by a factory method• the client is responsible for deleting them

– Iterators may have privileged access• friend class

– Iterators for composites– Null iterators

Page 37: Design Patterns

28-Feb-09 37

Iterator Pattern

• Sample Code – Follows in the next few slides.

Page 38: Design Patterns

28-Feb-09 38

Iterator Pattern

template <class Item>

class List {

public:

List(long size = DEFAULT_LIST_CAPACITY);

long Count() const;

Item& Get(long index) const;

// ...

};

Page 39: Design Patterns

28-Feb-09 39

Iterator Pattern

template <class Item>class Iterator {public:

virtual void First() = 0;virtual void Next() = 0;virtual bool IsDone() const = 0;virtual Item CurrentItem() const = 0;

protected:Iterator();

};

Page 40: Design Patterns

28-Feb-09 40

Iterator Pattern

template <class Item>class ListIterator : public Iterator<Item> {public:

ListIterator(const List<Item>* aList);virtual void First();virtual void Next();virtual bool IsDone() const;virtual Item CurrentItem() const;

private:const List<Item>* _list;long _current;

};

Page 41: Design Patterns

28-Feb-09 41

Iterator Pattern

template <class Item>ListIterator<Item>::ListIterator (const List<Item>* aList) : _list(aList), _current(0) {}

template <class Item>void ListIterator<Item>::First () {

current = 0;}

Page 42: Design Patterns

28-Feb-09 42

Iterator Pattern

template <class Item>void ListIterator<Item>::Next () {

current++;}

template <class Item>bool ListIterator<Item>::IsDone () const {

return _current >= _list->Count();}

Page 43: Design Patterns

28-Feb-09 43

Iterator Pattern

template <class Item>

Item ListIterator<Item>::CurrentItem () const {

if (IsDone()) {

throw IteratorOutOfBounds;

}

return _list->Get(_current);

}

Page 44: Design Patterns

28-Feb-09 44

Iterator Pattern

void PrintEmployees (Iterator<Employee*>& i) {for (i.First(); !i.IsDone(); i.Next()) {

i.CurrentItem()->Print();}

}List<Employee*>* employees;// ...ListIterator<Employee*> forward(employees);ReverseListIterator<Employee*> backward(employees);PrintEmployees(forward);PrintEmployees(backward);

Page 45: Design Patterns

28-Feb-09 45

Iterator Pattern

• Known Uses– Iterators are common in object-oriented systems

• Related Patterns– Composite:

• Iterators are often applied to recursive structures such as Composites.

– Factory Method: • Polymorphic iterators rely on factory methods to instantiate

the appropriate Iterator subclass.– Memento:

• Often used in conjunction with the Iterator pattern. An iterator can use a memento to capture the state of iteration. The iterator stores the memento internally.

Page 46: Design Patterns

28-Feb-09 46

Catalogue of Design Patterns (GoF)

Purpose

Creational Structural Behavioral Class Factory Method Adapter Interpreter

Template Method

Sco

pe

Object Abstract Factory Builder Prototype Singleton

Adapter Bridge Composite Decorator Facade Proxy

Chain of Responsibility Command Iterator Mediator Memento Flyweight Observer State Strategy Visitor

Page 47: Design Patterns

28-Feb-09 47

Page 48: Design Patterns

28-Feb-09 48

Visitor Pattern

• Problem– Consultant in an Office

• Solution

• Consequences

Page 49: Design Patterns

28-Feb-09 49

Factory Pattern

• Problem– Bread Maker

• Solution

• Consequences

Page 50: Design Patterns

28-Feb-09 50

Façade Pattern

• Problem– Façade Website

• Solution

• Consequences

Page 51: Design Patterns

28-Feb-09 51

Singleton Pattern

• Problem:– Managing entities with one-instance-at-a-time– Office of the Principal of MSIT– Heart in a Human Body– cout, cin, cerr, clog …

• Solution:• Consequences:

– Synchronization needed for multi-threaded use

• Note:– Closely related to Monostate Pattern

Page 52: Design Patterns

28-Feb-09 52

Thank You

Page 53: Design Patterns

28-Feb-09 53

Pattern’s Everywhere in Life• Pattern in Nature

– Summer, Winter, Autumn: Climatic Pattern– New Moon, Full Moon: Lunar Pattern– Iron Filings in a Magnetic Fields: Magnetic Pattern

• Patterns in Art/ Humanities

– Bhairavi, Malkosh, Hansadhwani: Musical Pattern– Sonnet: Poetic Pattern– Bibi #1, Hero #1, Jodi #1, Premi #1: Bollywood Pattern– Heshtoric Win, The Damned: Media Pattern– Simple, Complex, Compound Sentences: Grammatical Pattern

• Patterns in Sport

– 4-3-3, 5-2-3, 10: Soccer Pattern– Castling: Chess Pattern

• Patterns in Crime / Politics

– BTK, Stone Man: Serial Killer Pattern– 9/11, 7/11, 26/11: Terror Pattern – Mughal, Gandhi: Dynastic Pattern

• Patterns in Construction

– Baluchari, Benarasi, Pachhampalli: Silk Pattern– Palace, House, Apartment, Condo: Housing Pattern– Recipe: Cooking Pattern– Times New Roman, Arial, Verdana, Tahoma: Typesetting Pattern

• Patterns in Computation

– Semi-Group, Monoid, Group, Abelian Group: Algebraic Pattern– Unconditional Branch, Conditional Branch, Definite Loop, Indefinite Loop, Recursion: Programming Pattern– Divide-and-Conquer, Greedy, Dynamic Programming, Branch-and-Bound: Algorithmic Patterny– Factory, Iterator, Visitor, Singleton: Design Pattern