; pattern
Learning Center
Plans & pricing Sign in
Sign Out
Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>



  • pg 1
									Components Based Software

       Design Patterns

    Why read if you can watch?

           Design patterns
• The reference for
  design patterns
• “Gang of four”
• Based on Erich
  Gamma’s Ph.D.

         What is Design Pattern?
• inheritance allows related classes to share code,
  thus, allowing for code reusability, flexibility, etc.
• How about unrelated classes - can we make them
• Experience in the object-oriented design community
  has shown that interaction among even unrelated
  objects often takes the form of a recurring pattern or
  set of patterns.
• A number of these patterns have been identified
  and are being referred to as object-oriented design
    What is a design pattern?

• A solution for a recurring problem
  in a large OOP system
• A pattern is the outline of a
  reusable solution to a general
  problem encountered in a
  particular context

• Christopher Alexander, a professor
  of architecture…
  –“A pattern describes a problem which
   occurs over and over again in our
  –and then describes the core of the
   solution to that problem,
  –in such a way that you can use this
   solution a million times over,
  –without ever doing it the same way
• Jim Coplein, a software engineer:
• What are dress patterns?
  – “... I could tell you how to make a dress by
    specifying the route of a scissors through a piece
    of cloth in terms of angles and lengths of cut. Or, I
    could give you a pattern.
  – Reading the specification, you would have no
    idea what was being built or if you had built the
    right thing when you were finished.
  – The pattern is the rule for making the thing, but it
    is also, in many respects, the thing itself.”
• A design pattern is not a finished design that
  can be transformed directly into code.
• It is a description or template for how to solve
  a problem that can be used in many different
• A component, as a reusable entity, can be
  seen as a realization of some design pattern.
         Patterns in engineering
• How do other engineers find and use patterns?
  – Mature engineering disciplines have handbooks
    describing successful solutions to known
  – Automobile designers don't design cars from
    scratch using the laws of physics
  – Instead, they reuse standard designs with
    successful track records, learning from
  – “Be sure that you make everything according to the
           Design Patterns
• Design is blue print or sketch of
  something so it can be defined as
  creation of something in mind
• Pattern is defined as guideline or
  something that repeats
• Design Pattern becomes creating
  something in mind that repeats or
 capturing design ideas as a "pattern" to
               the problems.          11
• Database normalization.
• Normalization is a pattern (Core solution
  to database design)
• but what level of normalization needs
  (exact solution) depends on requirement
  and context.

       Design Patterns are NOT
• Data structures that can be encoded in classes and
  reused as is (i.e., linked lists, hash tables)
• Complex domain-specific designs
  (for an entire application or subsystem)

• They are:
   – “Descriptions of communicating objects and
     classes that are customized to solve a general
     design problem in a particular context.”
    Design Pattern Elements
1- Pattern Name
•    Handle used to describe the design
•    Increases vocabulary
•    Evaluation without implementation
     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
     Design Pattern Elements
3. Solution
•    Describes elements for the design
•    Includes relationships, responsibilities,
  and collaborations
•    Does not describe concrete designs or
     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
Multiple Displays Example
         The Observer pattern
• Name
  – Observer.
• Description
  – Separates the display of object state from the object
• Problem description
  – Used when multiple displays of state are needed.
• Solution description
  – UML description.
• Consequences
  – Optimisations to enhance display performance are
Observer pattern

                                                      depends on
depends on
                        is presented as


     Subject                              Observer                      Subject                Observer 1       Observer 2
              state                              update
              detach               ConcreteObserver                               attach(this)
             setData                              update
             getData                         doSomething            setData

                         state = X;
                         notify();                                                   getData


              for all observers                                                                             update
             in observerList do
                     notify();                                                       getData
        Types of design patterns
• Design patterns can be (roughly) grouped
  into three categories:
• Creational patterns
     – Constructing objects
• Structural patterns
     – Controlling the structure of a class
• Behavioral patterns
     – Deal with how the object behaves
      Types of design patterns
• Structural Patterns
  – Focus: How objects are composed to form larger
  – Examples: composite, adapter, bridge, proxy
• Behavioral Patterns
  – Focus: Algorithms and the assignment of
    responsibilities to objects
  – Examples: command, observer, strategy
• Creational Patterns
  – Focus: Creation of complex objects
  – Examples: abstract factory, builder
                 Categories of Design Patterns

 Purpose      Design Pattern           Aspects that can vary

Creational      Abstract Factory   Families of product objects

                 Builder           Creation of a composite object
                 Factory Method    Subclass of object instantiated

Structural        Adapter            Interface to an object

                 Facade              Interface to a subsystem

                 Flyweight          Storage costs of objects

                  Proxy              How an object is accessed

 Behavioral       Command          When & how a request is fulfilled
                  Iterator           Traversal of elements in an
Design Space Patterns

         Creational patterns
• Design patterns that deal with object
  creation mechanisms, trying to create
  objects in a manner suitable to the
• Make a system independent of the way in
  which objects are created, composed
  and represented
        Creational patterns
• Encapsulate knowledge about which
  concrete classes the system uses (so
  we can change them easily later)
• Hide how instances of these classes
  are created and put together (so we
  can change it easily later)
           Creational Patterns
• class-scoped patterns
  – uses inheritance to choose the class to be
    • Factory Method
• object-scoped patterns
  – uses delegation
    •   Abstract Factory
    •   Builder
    •   Prototype
    •   Singleton
             Pattern Example: “Singleton”
• Problem
  – Want to ensure a single instance of a class, shared by all
    uses throughout a program
• Context
  – Need to address initialization versus usage ordering
• Solution
  – Provide a global access method (e.g., a static member
  – First use of the access method instantiates the class
  – Constructors for instance can be made private
• Consequences
  – Object is never created if it’s never used
  – Object is shared efficiently among all uses
        Structural patterns
• Describe ways to assemble
  objects to realize new
 –Added flexibility inherent in object
  composition due to ability to
  change composition at run-time
 –not possible with static class
        Structural patterns
• Example: Proxy
 –Proxy: acts as convenient surrogate
  or placeholder for another object.
   • Remote Proxy: local representative
     for object in a different address
   • Virtual Proxy: represent large object
     that should be loaded on demand
   • Protected Proxy: protect access to
     the original object
            Structural Patterns
• Adapter:
   – Translator adapts a server interface for a client
• Bridge:
   – Abstraction for binding one of many implementations
• Composite:
   – Structure for building recursive aggregations
• Decorator:
   – Decorator extends an object transparently
• Facade:
   – Simplifies the interface for a subsystem
• Flyweight:
   – Many fine-grained objects shared efficiently.
• Proxy:
   – One object approximates another
             Behavioral Patterns
• Chain of Responsibility:
   – Request delegated to the responsible service provider
• Command:
   – Request or Action is first-class object, hence re-storable
• Iterator:
   – Aggregate and access elements sequentially
• Interpreter:
   – Language interpreter for a small grammar
• Mediator:
   – Coordinates interactions between its associates
• Memento:
   – Snapshot captures and restores object states privately

Which ones do you think you have seen somewhere?
     Behavioral Patterns (cont.)
• Observer:
   – Dependents update automatically when subject
• State:
   – Object whose behavior depends on its state
• Strategy:
   – Abstraction for selecting one of many algorithms
• Template Method:
   – Algorithm with some steps supplied by a derived
• Visitor:
   – Operations applied to elements of a heterogeneous
     object structure
                  Pattern : “Command”
• Problem
  – Want to issue requests to objects
  – Don’t know in advance which request(s) will be made
  – Don’t know in advance to what object(s) they will go
• Solution core
  – Encapsulate function call parameters and target object
    reference inside an “execute” method
• Consequences
  – Decouples invocation/execution
  – Commands are first-class objects (elevates functions)
  – Easy to compose, add new ones
    Structure Diagram Example: “Command”
• Shows fixed class/interface roles in the pattern
• Shows fixed relationships between roles
 <<Client>>       client role            command role

                                     *    <<Command>>
                                          execute ( )

              <<Receiver>>               execute ( )
              action(args)                    state_
              Symbol                            Meaning


                                          Object A instantiates B
A                          B


                                             B is a subclass of A

                                                Comment box


class method           o             Implementation pseudocode
                Object Interface
Class diagram
                     Every method in the class has its own
                     unique signature

                    return_type   name    (parameter types)

                     The set of all signatures defined by
                     an object’s methods or operations is
  methods            called the object interface.

                     This interface characterizes the
                     complete set of requests that can
                     be sent to the object.
           Specifying Object Interfaces

Signature of a method:
        name•                                  ClassA

        parameters•                  int metod1(int param);
       return type•                   void resize( );


   int metod1(int param);
                                      int metod1(int param);
     void resize(                     void resize( );

                                 Possible message recipients
         Implementation of an Interface in C++

Interface provided by an        Concrete realizations receive
abstract class                  the messages

                                  virtual double area( ) ;
  virtual double area( ) = 0;     virtual void draw( ) ;
                                   virtual void
  virtual void draw( ) = 0;               resize(int scale) ;
 virtual void
       resize(int scale) = 0;             Rectangle

                                   virtual void draw( ) ;
                                  virtual double area( ) ;
                                  virtual void
                                        resize(int scale) ;
         Class Hierarchy


Rectangle                        Circle

                 Messages directed to a Shape object
Square           can be received by instances of any of
                 these concrete classes.
     AutoComplete design pattern
When to Use This Pattern
• The suggestions can be pulled from a manageable set of data.
• The input item can be entered in multiple ways.
• The input item can be matched with a specific data item in the system.
• Speed and accuracy of entry is an important goal.
• The total number of items would be too large or inconvenient for
  displaying in a standard drop down box.

           Booking design pattern

• How
• Booking a flight/car/holidays is in structure very similar to other online purchasing or ordering activities. It consists of two high-level
  steps:Determining the item to book/buy using a search-like process.
• Going through the Purchase Process for the selected item(s).
• The trickiest part of the booking is the searching and selecting of the item. In many cases, such as on a Travel Site, you'll find a box containing
  some variation onAdvanced Search on the Homepage. See the example above from Expedia. Such aForm is the start of a series steps the users
  have to go through using a Wizard:

  The basic steps are:Initial selection. Users can narrow down their preferences for dates, prices, type of fare (if applicable), sort of transport, and
  the number of persons.
• Perform a search in the database. Users will see a Processing Page while the system is searching because it usually takes quite long before
  the search is completed.
• Show the results. The results are basically a special case of Search Results. The main problem here is how to deal with the combination of
  dates and prizes. One approach is to search primarily on date or price as the user requests. Another approach is not ask the user the set search
  type first but instead to combine price and dates. Primarily the results are sorted by date but with an indication of the prices. For example, using
  color coding. See British Airways example below. Narrow down dates first, then prizes. There are many ways that the combination of prices and
  dates can be handled, for example using a or calendar views with color coding.

  Problem summary
  The user needs to skim through stories without scrolling or any other unnecessary mouse movements.

A slideshow shows several stories with images, one at a time. After a specific set time
interval one story is replaced by another – often with an animated transition.
Transitions between images are most often a sliding effect although a simple fade is
also a popular choice. The most important design choice when it comes to transitions
is to make it seem natural. Animations should never be used for showing off; only to
support the usability and understandability of UI.
Numbers, bullets, or thumbnails
Use numbers, bullets, squares, or thumbnails to represent all the images in the
slideshow. These provide a way of letting the user have a sense of where he or she is
in the slideshow and help set expectations as to how many stories are left and
Use numbers if it’s important to let the user now exactly how many stories a slideshow
has. Use bullets if it doesn’t matter, and thumbnails if you want to inspire the user to
jump past the sequential order of stories that you’ve chosen beforehand.
Focus attention
Slideshows steal attention! Especially if they are combined with animated transitions.
Put slideshows together with blinking advertisement and other bright, animated or
otherwise attention-stealing elements on the page and you have mayhem. If more than
one element screams for attention, the user will get lost. If you have multiple elements
that scream for attention other than the slideshow, the slideshow will only help diffuse
users’ attention instead of focusing it.
Consider whether your slideshow is going to represent the main and most important
stories of your site – if it doesn’t, then leave out the slideshow. A slideshow directs
attention towards itself. Don’t overdo it.
Buttons and good callout texts
Increase the effectiveness of your slideshow by adding buttons for each story that calls
out for attention. Buttons help users know what to click. However, be careful not to fall
in the common trap of just labeling your button with “Read more”, unless that is really
the only action the user can do by clicking on that button. Texts like “Support”,
“Donate”, “Buy”, and “Watch video” are much more effective in getting users to click
and set expectations of what they will get.
Common navigation elements include:
Previous and next buttons
Bullets, numbers, or thumbnails

To top