Você está na página 1de 45

Design Patterns Introduction

K. Meena SymIndia Training & Consultancy Pvt Ltd Bangalore www.symindia.com meena@symindia.com

SymIndia

Design Patterns/1

Coverage

Need

Features

SymIndia

Design Patterns - Intro/2

Problem Solving

Given a problem you encounter, how do you go about solving it?

Repairing your bike Making Coffee Fixing a leak in a pipe Can we afford to? Should we re-use the learning in future?
Does this mean that our creativity is curbed?

Do we start from scratch (always!) ?

Do we seek guidance from an expert?

Do we get accustomed to common terms? When do we say that the solution is elegant?
Design Patterns - Intro/3

SymIndia

Why Patterns ?

Solve "real world" problems Capture domain expertise Document design decisions and rationale Reuse wisdom and experience of master practitioners Explain "Best-fits" for the given set of concerns/trade-offs Form a shared vocabulary for problemsolving discussion
Design Patterns - Intro/4

SymIndia

Need contd

Not enough to just solve the problem

Context (When and Where)

Forces (trade-off alternatives, misfits, goals+constraints) Resolution (how and why the solution balances the forces)

SymIndia

Design Patterns - Intro/5

Conclusion

Why re-invent the wheel? Avoid re-designing, at least minimize Not every problem needs to be solved from first principles!

Recurring patterns to specific design problems


Flexibility Elegance Re-usability

SymIndia

Design Patterns - Intro/6

Pattern origins and history

Writings of architect Christopher Alexander

(coined this use of the term "pattern" ca. 19771979)

Kent Beck and Ward Cunningham, Textronix, OOPSLA'87

(used Alexander's "pattern" ideas for Smalltalk GUI design)

Erich Gamma, Ph. D. thesis, 1988-1991


Design Patterns - Intro/7

SymIndia

Pattern origins and history

James Coplien, Advanced C++ Idioms book, 19891991 Gamma, Helm, Johnson, Vlissides ("Gang of Four GoF)

Design Patterns: Elements of Reusable ObjectOriented Software, 1991-1994

Buschmann, Meunier, Rohnert, Sommerland, Stal,

Pattern -Oriented Software Architecture: A System of Patterns (POSA book)


SymIndia

Design Patterns - Intro/8

Definitions

a fully realized form, original, or model accepted or proposed for imitation[dictionary] the abstraction from a concrete form which keeps recurring in specific non-arbitrary contexts [Riehle] both a thing and the instructions for making the thing [Coplien] ...a literary format for capturing the wisdom and

experience of expert designers, and communicating it to novices

SymIndia

Design Patterns - Intro/9

What does a design Pattern do?


Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to the problem . In such a way that you can use this solution a million times over , without ever doing it the same way twice
- Christopher Alexander about Patterns in Buildings and Towns

SymIndia

Design Patterns - Intro/10

Overview of Patterns
Present solutions to common software problems arising within a certain context Help resolve key software design forces Flexibility Extensibility Dependability Predictability Scalability Efficiency

Capture recurring structures & dynamics among software participants to facilitate reuse of successful designs
AbstractService
service Client

Generally codify expert knowledge of design strategies, constraints & best practices

Proxy

Service
1 1

SymIndiaThe Proxy Pattern

service

service

Design Patterns - Intro/11

DP vs Data Structures & Algorithms

Data Structures and Algorithms are used in the implementation of Patterns They solve more fine-grained computational problems

Sorting, Searching Focus on efficiency and optimization tradeoffs and compromises, communicating commonality

They are rarely concerned with issues like

SymIndia

Design Patterns - Intro/12

Patterns vs. Framework

FrameWork

A framework is a set of cooperating classes that make up a reusable design for a specific class of software The framework captures the design decisions that are common to its application domain A developer customizes a framework to a particular application by sub-classing and composing instances of framework classes A single framework typically encompasses several design patterns

SymIndia

Design Patterns - Intro/13

Contd

Frameworks are the physical realization of one or more software pattern solutions

SymIndia

Design Patterns - Intro/14

Patterns do

provide common vocabulary

provide shorthand for effectively communicating complex principles


help document software architecture capture essential parts of a design in compact form show more than one solution describe software abstractions
Design Patterns - Intro/16

SymIndia

Patterns are NOT


Solutions that have worked only once Providing exact solutions Abstract Principles or Heuristics Universally applicable in all contexts Untested Ideas/theories Panacea Restricted to Software/OO design
Design Patterns - Intro/17

SymIndia

Be(a)ware of the Hype

Just because something is not a pattern does not mean it is not any good! If something is a pattern, then (hopefully) it is good!

SymIndia

Design Patterns - Intro/18

Ingredients
Pattern Context a design situation giving rise to a design problem Problem a set of forces occuring in that context Solution a form or rule that can be applied to resolve these forces

Example window place

forces

he wants to sit down and be comfortable he is drawn toward the light

solution

in every room, make at least one window into a window place SymIndia

Design Patterns - Intro/19

Types of software patterns

Design patterns (software design) (POSA)


architectural (systems design) design (micro-architectures) [Gamma-GoF] idioms (low level)

Analysis patterns (recurring & reusable


analysis models) [Flower]

Organization patterns (structure of


organizations/projects)

SymIndia

Process and Domain-specific Patterns


Design Patterns - Intro/20

GoF format
Pattern name and classification Intent what does pattern do / when the solution works Also known as other known names of pattern (if any) Motivation the design problem / how class and object structures solve the problem
SymIndia
Design Patterns - Intro/21

GOF Format
Applicability situations where pattern can be applied Structure a graphical representation of classes in the pattern Participants the classes/objects participating and their responsibilities Collaborations of the participants to carry out responsibilities
SymIndia

Design Patterns - Intro/22

GoF format
Consequences trade-offs, concerns Implementation hints, techniques Sample code code fragment showing possible implementation
SymIndia
Design Patterns - Intro/23

GOF Format
Known uses patterns found in real systems Related patterns closely related patterns

SymIndia

Design Patterns - Intro/24

DP catalog - GoF
Purpose

Creational
Class

Structural Adapter Adapter Bridge Composite Decorator Facade Flyweight Proxy

Behavioral Interpreter Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor Template method

Factory Method Abstract Factory Builder Prototype Singleton

Scope Object

SymIndia

Design Patterns - Intro/28

An Example, A Payroll App

Requirements

Estimate amount of money that employee can expect to see in his/her next paycheck Complex calculations based on varying country and local taxes + retirement contributions Operates in London/NY and may open up other offices over the next few years Predicted that the Personnel Manager had plans for the introduction of a second retirement plan

What would YOU do?


Design Patterns - Intro/29

SymIndia

Two Possible Approaches


Approach 1
TakeHomePay +GetTakeHome() USNYCNoRetirement +GetTakeHome() UKLondonTaxRetirement +GetTakeHome() USNYCTaxRetirement +GetTakeHome()

UKLondonNoRetirement +GetTakeHome()

Approach 2
<<Interface>> TakeHomePay +GetTakeHome()

CommonTakeHomePay +GetTakeHome()

Decorator +GetTakeHome()

LondonTax

NYCTax +GetTakeHome()

UKTax +GetTakeHome()

USATax +GetTakeHome()

RetirementPlan +GetTakeHome()

SymIndia

+GetTakeHome()

Design Patterns - Intro/30

But what if?

Second retirement plan introduced and new office opened?


Approach #1
TakeHomePay +GetTakeHome()

Approach #2
<<Interface>> TakeHomePay +GetTakeHome() *

1
UKLondonTaxNoRetirement +GetTakeHome() UKLondonTaxRetirementA +GetTakeHome() UKLondonTaxRetirementB +GetTakeHome() USNYCTaxNoRetirement +GetTakeHome() USNYCTaxRetirementA +GetTakeHome() USNYCTaxRetirementB +GetTakeHome() USMiamiTaxNoRetirement

Employee
+GetTakeHome() USMiamiTaxRetirementA +GetTakeHome() USMiamiTaxRetirementB +GetTakeHome()

Decorator +GetTakeHome()

+GetTakeHome()

UKTax +GetTakeHome() LondonTax +GetTakeHome() NYCTax +GetTakeHome()

USATax +GetTakeHome() MiamiTax

RetirementPlanA +GetTakeHome()

RetirementPlanB +GetTakeHome()

+GetTakeHome()

SymIndia

Design Patterns - Intro/31

Some Terms

Class

Defines how an object is implemented Describes internal state and implementation of its operations Refers only to its interface Implementation Inheritance Share code and representation

Type/Interface

Class/Implementation Inheritance

Interface Inheritance

SymIndia

Design Patterns - Intro/32

Implementation Inheritance

Merits

Inherit both WHAT and HOW If base class functionality is fine, Do nothing in the derived class Fragile Base Class problem

Demerits

Tight Coupling

A class, once published, cannot be altered New methods, Change in existing methods signature/body If a class is substituted with another , user code has to be recompiled

Direct Support in Java, C++, C#, VB.NET


Design Patterns - Intro/33

SymIndia

Interface Inheritance

Merits

Delink WHAT from HOW Skill sets to define are different from skill sets to implement Loose coupling

Demerits

User code works only with Interface Change in class does not impact user

Direct Support in VB 6, Java, C#, VB.NET

Workaround in C++

SymIndia

Design Patterns - Intro/34

Fundamental to Re-use

Program to an interface, not an implementation !

SymIndia

Design Patterns - Intro/35

Benefits

Clients remain unaware of the specific types of objects they use. 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.
Design Patterns - Intro/36

SymIndia

Re-use Mechanisms

Inheritance

Re-use by subclassing White-box Approach Assembling/composing objects to get complex functionality Black-box re-use

Composition

SymIndia

Design Patterns - Intro/37

Inheritance

Merits

Easy to use Easy to override/enhance Cannot change implementations at run-time If parent class changes, sub classes are also to be changed

Demerits

SymIndia

Design Patterns - Intro/38

Composition

Merits

Defined dynamically at run time Smaller class hierarchies More objects Mere assembling may not suffice

Demerits

SymIndia

Design Patterns - Intro/39

Fundamental to Re-use

Favor Object Composition over Class Inheritance !

SymIndia

Design Patterns - Intro/40

Delegation
Composition as powerful for reuse as inheritance

Two objects involved in handling requests Explicit object references Easy to compose behaviors at runtime
Window rectangle Area() Area() width height Rectangle

return rectangle->Area()

return width * height

But: Dynamic, hard to understand, run-time inefficiencies

SymIndia

Design Patterns - Intro/41

Typical Scenarios

While creating an object, we dont want to commit to a specific implementation A request is not always handled in just one way

Should be able to change , both at compile time and at run time

S/w should not be tied to a particular platform


Design Patterns - Intro/42

SymIndia

Typical Scenarios

Client should not know anything about an objects representation, location or storage No tight coupling among objects Avoid too much of subclassing How to add new functionality to classes? How to add new responsibilities to specific objects?
Design Patterns - Intro/43

SymIndia

Designing for Change

Dependence on specific operations


Commits to one way of satisfying a request Compile-time and runtime modifications to request handling can be simplified by avoiding hard-coded requests Patterns: Chain of Responsibility, Command

SymIndia

Design Patterns - Intro/45

Designing for Change

Dependence on object representations or implementations

Clients dont know how an object is represented, stored, located, or implemented Hide information from clients to avoid cascading changes Patterns: Abstract factory, Bridge, Memento, Proxy

SymIndia

Design Patterns - Intro/47

Designing for Change

Tight coupling

Leads to monolithic systems Tightly coupled classes are hard to reuse in isolation Patterns: Abstract Factory, Bridge, Chain of Responsibility, Command, Facade, Mediator, Observer

SymIndia

Design Patterns - Intro/49

Designing for Change

Inability to alter classes conveniently


Sources not available Change might require modifying lots of existing classes Patterns: Adapter, Decorator, Visitor

SymIndia

Design Patterns - Intro/51

Relationships
Memento Proxy Builder saving state of iteration Iterator Enumerating children Composite Decorator adding respnsibilities to objects sharing composites defining grammar Interpreter Chain of Responsibility composed using Command Adapter Bridge

changing skin versus guts

Flyweight

Visitor

Strategy

sharing strategies State

Mediator

Observer

Prototype

defining algorithms steps single instance

Template Method

Factory Method

Abstract Factory single instance Facade

Singleton

SymIndia

Design Patterns - Intro/52

Questions?

SymIndia

Design Patterns - Intro/53

Você também pode gostar