design patterns n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Design Patterns PowerPoint Presentation
Download Presentation
Design Patterns

Loading in 2 Seconds...

play fullscreen
1 / 59

Design Patterns - PowerPoint PPT Presentation


  • 101 Views
  • Uploaded on

Design Patterns. Ever present problems. Software engineers have to solve every day a lot of different problems of different nature. The effectiveness of an engineer is measured by the time he/shee needs to diagnose, identify, and solve these problems.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Design Patterns' - kaida


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
ever present problems
Everpresentproblems
  • Software engineers have to solve every day a lot of different problems of different nature.
  • The effectiveness of an engineer is measured by the time he/shee needs to diagnose, identify, and solve these problems.
  • The best engineer is who is able to apply the same solution (or similar) to solve similar problems.
reinventing the wheel
Reinventingthewheel?
  • The idea that object-oriented design is based on of not reinventing the wheel is referred to the programmign process. So, why don’t we apply it during the analysis and design?
  • We need a way the share with other engineers the solutions we apply to these ever recurring problems.
  • So, we need to document these effective designs to make the communication easier.
adaptation to the change
Adaptationtothechange
  • Designing object-oriented software is hard, but designing reusable object-oriented software is even harder.
  • Design must be specific for the problem, but flexible enough to adapt it to future changes in the requirements avoiding as far as possible the redesign.
fexible designs
Fexibledesigns
  • Therefore... We need a flexible design.
  • And so... How do the good object-oriented designers do?
    • The have a great experience, because,
      • It takes a long time to learn to do good object-oriented designs.
      • Novice designers are prone to apply old non object-oriented techniques.
typical problems hard to solve on oo
Typicalproblemshardtosolveon OO
  • How can I represent states using objects?
  • How can I guarantee that there will be one only instance of one specific class?
  • How can I add responsabilities dinamically –without using inheritance?
why a design pattern
Why a Design Pattern?
  • Reusability:one of Wasserman’s rules(1996)for an efficient and actual SE discipline
  • Helping new designers to have a more flexible and reusable design
  • Improving the documentation and maintenance of existing system by furnishing an explicit specification of class and object interactions and their intent

Design Patterns

history of design pattern
History of Design Pattern
  • 1979:Christopher Alexander,architect, “The Timeless Way of Building”,Oxford Press
  • 1987:OOPSLA (Object Oriented Programming System),Orlando, presentation of design pattern to the community OO by Ward Cunningham and Kent Beck
  • 1995:Group of Four alias E.Gamma, R.Helm,R.Johnson and J.Vlissides : “Design Pattern:Elements of Reusable OO software”

Design Patterns

gang of four
Gang of Four
  • Pattern-based design was introduced into architecture and engineering in the 1950's
  • Almost immediately, software engineers began using patterns for designing software
  • It wasn't until a group of four researchers combined forces that pattern-based design became well-known and commonplace
    • This group was known as the gang of four (GoF)
gang of four1
Gang of Four
  • The gang of four (GoF) is:
    • Erich Gamma
    • Richard Helm
    • Ralph Johnson
    • John Vlissides
  • They are the authors of the famous text "Design Patterns: Elements of Reusable Object-Oriented Software"
but what is a design pattern
But... What is a design pattern?
  • A pattern is an idea that has been useful in one practical context and will probably be useful in others
    • Martin Fowler
  • A pattern is a three-part rule, which expresses a relation between a certain context, a problem, and a solution
    • Christopher Alexander
a patterns as a schema
A patterns as a schema
  • A software design pattern provides a schema
    • It’s not an implemented artifact ready to be used (like utility classes or libraries)
    • It’s a mental built block to be implemented in many different applications and contexts.
      • There won’t be two identical implementations of the same pattern
      • The pattern does not define the relation between classes, but between the roles that classes play in the pattern.
      • Once the pattern is applied, the roles that each class plays in the pattern should be identified.
and why should we apply them
And... Why should we apply them?
  • Using patterns offers a few key advantages:
    • Leverage a proven solution
    • Provide a common vocabulary
leverage a proven solution
Leverage a Proven Solution
  • The solution for a pattern has been designed, implemented and tested
    • Reusing these solutions allows most of each of these steps to be eliminated
    • If the implementation of a pattern is used, the design, implementation, and testing are minimal just to ensure the proper behaviour exists
    • If the design of a pattern is used, the solution specific to the problem must be implemented and tested, but need not be redesigned
provide a common vocabulary
Provide a Common Vocabulary
  • Some patterns are very common
    • Documenting and cataloguing patterns allows designers and architects to describe a solution using patterns as part of the language
      • Typically, this can make descriptions of solutions shorter
    • Architects and designers can more easily communicate their designs to their developers
describing a pattern
Describing a pattern
  • More technical approach:

A design pattern is a descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context

  • A pattern is made by four elements:
    • name
    • problem
    • solution
    • consequences

Design Patterns

name of design pattern
Name of Design Pattern
  • Describe a design problems and its solutions in a word or two
  • Used to talk about design pattern with our colleagues
  • Used in the documentation
  • Increase our design vocabulary
  • Have to be coherent and evocative

Design Patterns

problem
Problem
  • Describes when to apply the patterns
  • Explains the problem and its context
  • Sometimes include a list of conditions that must be met before it makes sense to apply the pattern
  • Have to occurs over and over again in our environment

Design Patterns

solution
Solution
  • Describes the elements that make up the design, their relationships, responsibilities and collaborations
  • Does not describe a concrete design or implementation
  • Has to be well proven in some projects

Design Patterns

consequences
Consequences
  • Results and trade-offs of applying the pattern
  • Helpful for describe design decisions, for evaluating design alternatives
  • Benefits of applying a pattern
  • Impacts on a system’s flexibility,extensibility or portability

Design Patterns

description of design pattern
Description of Design Pattern
  • Pattern name and classification
    • contains the essence of pattern succinctly
    • Become part of your designvocabulary
  • Intent
    • What does the pattern do ?
    • What particular problem does it address ?

Design Patterns

description of design pattern1
Description of Design Pattern
  • Motivation
    • Illustrate a design problem and how the class and the object structures solve the problem
  • Applicability
    • In which situations the pattern can be applied?
    • How can you recognize these situations?

Design Patterns

description of design pattern2
Description of Design Pattern
  • Structure
    • Graphical representation of the classes and their collaborations in the pattern
  • Participants
    • Class
    • Objects
    • Responsibilities

Design Patterns

description of design pattern3
Description of Design Pattern
  • Collaborations
    • How the participants collaborate to carry out their responsibilities
  • Consequences
    • How does the pattern support its objectives?
    • What are the trade-offs and results of using the pattern?

Design Patterns

description of design pattern4
Description of Design Pattern
  • Implementation
  • Sample Code
  • Known Uses
    • Examples of the pattern found in real systems

Design Patterns

description of design pattern5
Description of Design Pattern
  • Related Patterns
    • What design patterns are closely related to this one?
    • What are the important differences?

Design Patterns

types of patterns
Types of patterns
  • There is first classification attending the abstraction level of the pattern:
    • Architectonic patterns
    • Design patterns
    • Code-focused patterns (idioms)
architectonic patterns
Architectonicpatterns
  • In a higher abstraction level, they define the architecture, the global structure of the system by means of subsystems and their relationships.
  • Example: Model-view-controller
design patterns1
Designpatterns
  • Midium abstraction level (design level)
    • More concrete that the architectural patterns, but still independent from the language.
  • Example: Observer
idioms
Idioms
  • Low-level patterns – coding
  • Most of them, language-specific.
  • They contribute to a uniform and consistent style of the programms in the specific language.
  • Example:
    • Coding stype guides
      • Smalltalk Best Practice Patterns (Kent Beck, 1997),
      • Effective C++ (Scott Meyers, 1997),
      • Java Style. Patterns for Implementation (Jeff Langr, 2000), etc.
idioms1
Idioms
  • Example:

Effective cause any Java-programmer undestand the pourpose of this code with a first quick look.

Iterator iterator = list.iterator();

while (iterator.hasNext())

{

Element object = (Element) iterator.next();

// ...

}

classification of design pattern
Classification of Design Pattern

By purpose and by scope

  • Creational patterns
    • Abstract the instantiation process
    • Make a system independent to its realization
    • Class Creational use inheritance to vary the instantiated classes
    • Object Creational delegate instantiation to an another object

Design Patterns

classification of design pattern1
Classification of Design Pattern
  • Structural patterns
    • Class Structural patterns concern the aggregation of classes to form largest structures
    • Object Structural pattern concern the aggregation of objects to form largest structures

Design Patterns

classification of design pattern2
Classification of Design Pattern
  • Behavioral patterns
    • Concern with algorithms and assignment of responsibilities between objects
    • Describe the patterns of communication between classes or objects
    • Behavioral class pattern use inheritance to distribute behavior between classes
    • Behavioral object pattern use object composition to distribute behavior between classes

Design Patterns

and now some case studies
And now, some case studies,…
  • Studying design patterns is not a trivial issue.
  • A design pattern can be understood in its own context, giving a solution for a problem
  • Let’s see a set of case studies that can be solved or simplified applying design patterns.
example
Example
  • Problem: I need a class “God” that can only have 1 instance.
  • Motivation:A God-object can do powerful things; one God-object is sufficient.For security I need to guarantee that there is indeed only one God-object, implying that it would be sufficient for me to monitor this single God.
  • Solution ??
solution1
Solution

Singleton Pattern

class God { … // fields and other methods here

private God() { ... } ;

static private God i = new God() ; public static God getInstance() { return i ; }

}

  • God
  • i: God
  • God()
  • + God getInstance()

pattern !

  • Singleton
  • i: Singleton
  • Singleton()
  • + Singleton getInstance()
problem salary administrator
Problem: salary administrator
  • A salary administrator is responsible for calculating yearly bonus of employees.The algorithm to calculate this differs depending on an employee’s function.
  • Direct solution:

List<Employee> elist

Class SalaryAdminstrator { …calcBonus() { for (Employee e : elist)

if (e.function == PROFESSOR) e.bonus = 0 else if (e.function == LECTURER) e.bonus = 1.9 * e.salary

else e.bonus = 1.1 * e.salary

}

solution exploit subclassing
Solution : exploit subclassing

Class SalaryAdminstrator { …calcBonus() {

for (Employee e : elist) e.calcBonus() }

salary

bonus

Employee

+ calcBonus()

calcBonus() { bonus = 0 }

calcBonus() { bonus = 1.9 * salary }

Secretary

+ calcBonus()

Lecturer

+ calcBonus()

Professor

+ calcBonus()

strategy pattern
Strategy Pattern

Client

Strategy

+ calc()

0..*

1

StrategyC

+ calc()

StrategyB

+ calc()

StrategyA

+ calc()

what are the main guidelines
What are the main guidelines ??
  • Modularity !
    • ExtensibilityWe should be able to extend a software without ‘changing’ the existing code.
    • ReusabilityWe should avoid replicating the same functionalities  error prone, and higher maintenance cost.
  • On the other hand, balance this with coupling/dependencyIncreasing the coupling also makes a software more error prone, and increases maintenance cost.
problem tables
Problem : tables
  • A program wants to calculate the number of cells that a given table has.A table consists of rows. Each row consists of cells, and may be of different length.
  • Direct solution :

Table

class App { ...numCells(Table t) {inti = 0 ; for (Row r : t.rows)

for (Cell c : r.cells) i++ ; return i ; }

rows

0..*

Row

cells

0..*

Cell

a nicer solution
A nicer solution

+ numOfCells() : int

0..*

Component

children

Cell

Composite

numOfCells() { return 1}

numOfCells() {

int k = 0 ; for (Component c : children)

k = k + c.numOfCells() ;

return k ;

}

Table

Row

Now "App" can just look like this :

class App { ...numCells(Component c) { return c.numOfCells() ; } ...

composite pattern
"Composite" Pattern

Component+ operation()

0..*

Client

children

Composite

+ operation()

+ add(Component c)

+ remove(Component c)

+ getChildren() : List<Component>

Cell

+ operation()

problem live charts

A

D

B

C

A

B

C

D

Problem: live charts

This picture is taken from A.P. Mathur, slides "Design Patterns", CS 406 Software Engineering I, Purdue Univ. 2001.

A=10

B=40

C=30

D=20

controller

  • We want to display this data in various charts.
  • There is a controller active that works on the data.
  • We want the change to be mirrored “live” in the charts.
let s look at similar but simpler problem
Let’s look at similar but simpler problem

Fahrenheit display

Celcius display

class Heater {

int temp ; Thermometer ct ; Thermometer ft ; ...

void change(int d) {

temp = temp + d ; ct.update(temp) ; ft.update(9*temp/5 + 32)

}

}

Heater

Controller

solution2
Solution

Make it so that we can add/remove thermometers.

class Heater {

private int temp ; public List<Thermometer> ts ; ...

void change(int d) {

temp = temp + d ;notify() ; } public void notify() { for (Thermometer t : ts) t.update(this) }

}

We can add/remove Thermometer to this list.

Here is where we will put the temperature conversion.

solution3
Solution

Thermometer

- temp : int

+ update(Heater)

Subject

+ add(Thermometer)

+ remove(Thermometer)

+ notify()

oberservers

0..*

FahThermometer

CelciusThermometer

Heater

- temp : int

update(h) { temp = h.temp }

update(h) { temp = 9*h.temp/5 + 32 }

observer pattern
Observer Pattern

Subject

+ add(Thermometer)

+ remove(Thermometer)

+ notify()

Observer

+ update(Subject)

oberservers

0..*

ConcreteObs2

ConcreteObs1

ConcreteSubject

slide51
MVC
  • Model View Controller : a variant of Observer Pattern

(Model)

(View) usually GUI

Subject

+ add(Thermometer)

+ remove(Thermometer)

+ notify()

Observer

+ update(Subject)

0..*

Controller

problem1
Problem
  • I need different kinds of thermometers, but the decision can only be done at the run time.

class Panel {

Themometer t ;

...

public Panel(Class tkind) {

if (tkind == CelciusThermometer.class) t = new CelciusThermometer()

else if (tkind == FarThermometer.class) t = new FarThermometer()

else ... // error !

... }

}

solution factory method pattern
Solution : Factory Method pattern

public Panel(Class tkind) {

t = ThermometerCreator.factoryMethod(tkind) ... }

ThermometerCreator

+ factoryMethod (Class) : Thermometer

static public factoryMethod(Class tkind) {

if (tkind == CelciusThermometer.class) return new CelciusThermometer()

else if (tkind == FarThermometer.class) return new FarThermometer()

else ... // error !

}

problem2
Problem

if (s.isEmpty()) return null ;

m = s.get(0) ;for (k : s) if (k.compareTo(m) > 0) m=k

return m ;

I need a method that calculates the max element of two lists.

class MyClass {

private Comparable max(List<Comparable> s) ...

Comparable max2(List<Comparable> s, List<Comparable> t) {

m1 = max(s) ;

m2 = max(t) ;

if (m1==null && m2==null) return null ;

if (m1==null) return m2 ;

if (m2==null) return m1 ;

if (m1.compareTo(m2) > 0) return m1 else m2 ;

}

}

solution4
Solution

abstract class TemplateSolution {

abstract Comparable max(List<Comparable> s)

Comparable max2(List<Comparable> s, List<Comparable> t) {

m1 = max(s) ;

m2 = max(t) ; ... // as before

}

Solution1

max(s) { // as before }

TemplateSolution

# max

+ max2

Solution2

max(s) { return s.get(0) }

template method pattern
Template Method pattern

ConcreteSolution1

TemplateSolution

# operation1(...) # operation2(...)...

+ templateMethod(...)

ConcreteSolution2

  • The template method specifies an algorithm over the operations.
  • Each concrete solution implements or overrides the operations.
  • Keep in mind that this also increases the coupling  if these operations may only be used in the way they're used by the template method.
folding over a structure
Folding over a structure
  • I want to write methods to:
    • count the sum of all cells in a component
    • return me the cell with the max value

children

Component

0..*

Cellvalue : int

Composite

direct solution visitor pattern
Direct solution & Visitor Pattern
  • We have to keep writing the recursion over the structure of Component!
  • Can't we get a fold-like solution here??
  • Yes, with the Visitor Pattern.

sumCell (Component u) { if (u instanceof Cell) return u.value ; Composite u_ = (Composite) u ;int k = 0 ;

for (Component v : u_.children) k = k + sumCell(v) ;

return k ; }

thanks

Thanks!!!

Any question?