SlideShare a Scribd company logo
Design Patterns Tutorials




Editor: Nguyễn Đức Minh Khôi
@Feb 2012, HCMC University of Technology
Email: nguyenducminhkhoi@gmail.com
Content
           Intro to Design Patterns

             Creational Patterns (A)

              Structural Patterns (B)

             Behavioral Patterns (C)

           Other stuffs and conclusion
2/7/2012                Design Pattern Tutorials   2
Intro to Design Patterns
• Object Oriented (OO) basics
      – Abstraction
      – Encapsulation
      – Inheritance
      – Polymorphism




2/7/2012                Design Pattern Tutorials   3
Intro to Design Patterns
• OO Principles
      – Encapsulate what varies
      – Favor composition over inheritance
      – Program to interfaces, not implementations
      – Strive for loosely coupled design between objects
        and interact
      – Only talk to your friends



2/7/2012                 Design Pattern Tutorials           4
Intro to Design Patterns
• OO Principles (cont.)
      – Classes should be open for extension but closed
        for modification
      – Depend on abstraction. Do not depend on
        concrete classes
      – Don’t call us, we’ll call you
      – A class should have one reason to change



2/7/2012                 Design Pattern Tutorials         5
Intro to Design Patterns
• OO rules:
      – A class A extends (inherits) a class B
        (A: subclass, B: superclass)
      – An interface extends an interface
      – A class implements an interface
      – Inheritance -> IS relationship
      – Composition -> HAS relationship



2/7/2012                  Design Pattern Tutorials   6
Intro to Design Patterns
  • What is Pattern?
           – Pattern is a solution to a problem in a context
           – Context: the situation in which the pattern apply
           – Problem: goal you are trying to achieve in this
             context (any constraints that occur in that context)
           – Solution: what you are after – general design that
             anyone can apply which resolves the goal and set
             of constraints


2/7/2012                      Design Pattern Tutorials         7
Intro to Design
Patterns
List of Design Patterns
and their relationship




2/7/2012                  Design Pattern Tutorials   8
Overview of Patterns




2/7/2012         Design Pattern Tutorials   9
Content
           Intro to Design Patterns

             Creational Patterns (A)

              Structural Patterns (B)

             Behavioral Patterns (C)

           Other stuffs and conclusion
2/7/2012                Design Pattern Tutorials   10
Creational Patterns




                     Singleton                   Abstract Factory


            Creational Patterns involve object instantiation
           and all provide a way to decouple a client from the
                      objects it needs to instantiate

2/7/2012                         Design Pattern Tutorials           11
Factory Method Pattern
• Intent: defines an interface for creating an object,
  but let subclasses decide which class to instantiate.
  Factory Method let a class defer instantiation to
  subclasses.
• Use the Factory Method pattern when:
      – a class can't anticipate the class of objects it must create.
      – a class wants its subclasses to specify the objects it
        creates.
      – classes delegate responsibility to one of several helper
        subclasses, and you want to localize the knowledge of
        which helper subclass is the delegate.

2/7/2012                      Design Pattern Tutorials                  12
Factory Method Pattern (cont.)




2/7/2012         Design Pattern Tutorials   13
Factory Method Pattern (cont.)
• Notes:
      – Also known as Virtual Constructor
      – Encapsulate objects creation
      – Rely on inheritance, object creation is delegated to
        subclasses with implement the factory method to
        create objects.
      – Promote loose coupling by reducing the dependency
        of your application to concrete classes
      – Are powerful technique for coding abstraction, not
        concrete classes
2/7/2012                  Design Pattern Tutorials             14
Abstract Factory Pattern
• Intent: Provides an interface for creating families of
  related or dependent objects without specifying
  their concrete classes
• Use the Abstract Factory pattern when:
      – a system should be independent of how its products are
        created, composed, and represented.
      – a system should be configured with one of multiple
        families of products.
      – a family of related product objects is designed to be used
        together, and you need to enforce this constraint.
      – you want to provide a class library of products, and you
        want to reveal just their interfaces, not their
        implementations.

2/7/2012                     Design Pattern Tutorials                15
Abstract Factory Pattern (cont.)




2/7/2012          Design Pattern Tutorials   16
Abstract Factory Pattern (cont.)
• Notes:
      – Also known as KIT
      – Rely on composition, object creation is
        implemented in methods exposed in the factory
        interface
      – Others like Factory Method!




2/7/2012                Design Pattern Tutorials        17
Singleton Pattern
• Intents: Ensure a class only has one instance, and
  provide a global point of access to it.
• Use the Singleton pattern when
      – there must be exactly one instance of a class, and it must
        be accessible to clients from a well-known access point.
      – when the sole instance should be extensible by
        subclassing, and clients should be able to use an extended
        instance without modifying their code.
      – Be careful with multithread!



2/7/2012                    Design Pattern Tutorials             18
Singleton Pattern (cont.)




2/7/2012            Design Pattern Tutorials   19
Content
           Intro to Design Patterns

             Creational Patterns (A)

              Structural Patterns (B)

             Behavioral Patterns (C)

           Other stuffs and conclusion
2/7/2012                Design Pattern Tutorials   20
Structural Patterns




Decorator           Adapter           Façade             Composite   Proxy



            Structural Patterns let you compose classes or
                    objects into larger structures


2/7/2012                      Design Pattern Tutorials                       21
Decorator Pattern
• Intent: Attach additional responsibilities to an object
  dynamically. Decorators provide a flexible alternative
  to subclassing for extending functionality.
• Use Decorator:
      – to add responsibilities to individual objects dynamically
        and transparently, that is, without affecting other objects.
      – for responsibilities that can be withdrawn.
      – when extension by subclassing is impractical. Sometimes a
        large number of independent extensions are possible and
        would produce an explosion of subclasses to support every
        combination. Or a class definition may be hidden or
        otherwise unavailable for subclassing.


2/7/2012                     Design Pattern Tutorials             22
Decorator Pattern (cont.)




2/7/2012            Design Pattern Tutorials   23
Decorator Pattern (cont.)
• Notes:
      – Also known as Wrapper
      – Decorator classes are the same type as the
        components they decorate, either through inheritance
        or interface implementation.
      – You can wrap a component with any number of
        decorators.
      – Decorators can result in many small objects in our
        design, and overuse can be complex.
      – Decorators are typically transparent to the client of
        the component
2/7/2012                  Design Pattern Tutorials         24
Adapter Pattern
• Intent: convert the interface of a class into another
  interface clients expect. Adapter lets classes work
  together that couldn't otherwise because of
  incompatible interfaces.
• Use the Adapter pattern when:
      – you want to use an existing class, and its interface does not
        match the one you need.
      – you want to create a reusable class that cooperates with
        unrelated or unforeseen classes, that is, classes that don't
        necessarily have compatible interfaces.
      – (object adapter only) you need to use several existing
        subclasses, but it's impractical to adapt their interface by
        subclassing every one. An object adapter can adapt the
        interface of its parent class.
2/7/2012                     Design Pattern Tutorials              25
Adapter Pattern (cont.)




2/7/2012           Design Pattern Tutorials   26
Adapter Pattern (cont.)
• Notes:
      – Implementing an adapter may require little work
        or a great deal of work depending on the size and
        complexity of the target interface
      – Adapter Pattern has 2 forms: object and class
        adapters. Class adapters require multiple
        inheritance
      – Adapter wraps an object to change its interface, a
        decorator wraps an object to add new behaviors
        and responsibilities

2/7/2012                 Design Pattern Tutorials        27
Facade Pattern
• Intent: Provide a unified interface to a set of
  interfaces in a subsystem. Facade defines a higher-
  level interface that makes the subsystem easier to
  use.
• Use the Facade pattern when:
      – you want to provide a simple interface to a complex
        subsystem.
      – there are many dependencies between clients and the
        implementation classes of an abstraction. you want to
        layer your subsystems.
      – Use a facade to define an entry point to each subsystem
        level. If subsystems are dependent, then you can simplify
        the dependencies between them by making them
        communicate with each other solely through their facades.
2/7/2012                    Design Pattern Tutorials           28
Facade Pattern (cont.)




2/7/2012          Design Pattern Tutorials   29
Facade Pattern (cont.)
• Notes:
      – A façade decouple a client from complex system
      – Implementing a façade requires that we compose
        the façade with its subsystem and use delegation
        to perform the work of the façade.
      – You can implement more than one façade for a
        subsystem.
      – A façade wraps a set of objects to simplify


2/7/2012                 Design Pattern Tutorials          30
Composite Pattern
• Intent: Compose objects into tree structures to
  represent part-whole hierarchies. Composite lets
  clients treat individual objects and compositions of
  objects uniformly.
• Use the Composite pattern when:
      – you want to represent part-whole hierarchies of objects.
      – you want clients to be able to ignore the difference
        between compositions of objects and individual objects.
        Clients will treat all objects in the composite structure
        uniformly.

2/7/2012                     Design Pattern Tutorials               31
Composite Pattern (cont.)




2/7/2012            Design Pattern Tutorials   32
Composite Pattern (cont.)
• Notes:
      – A composition provides a structure to hold both
        individual (leaf nodes) objects and composites
      – There are many design tradeoffs in implementing
        Composite. You need to balance transparency and
        safety with your needs




2/7/2012                Design Pattern Tutorials      33
Proxy Pattern
• Intent: Provide a surrogate or placeholder for
  another object to control access to it.
• Use the Composite pattern when:
      – you want to represent part-whole hierarchies of objects.
      – you want clients to be able to ignore the difference
        between compositions of objects and individual objects.
        Clients will treat all objects in the composite structure
        uniformly.




2/7/2012                     Design Pattern Tutorials               34
Proxy Pattern (cont.)




2/7/2012          Design Pattern Tutorials   35
Proxy Pattern (cont.)
• Notes:
      – Also known as Surrogate
      – The Decorator Pattern adds behavior to an object,
        while a Proxy controls access
      – Like any wrapper, proxies will increase the number
        of classes and objects in your designs
      – Types of proxy: Remote proxy, virtual proxy,
        protection proxy


2/7/2012                 Design Pattern Tutorials        36
Content
           Intro to Design Patterns

             Creational Patterns (A)

              Structural Patterns (B)

             Behavioral Patterns (C)

           Other stuffs and conclusion
2/7/2012                Design Pattern Tutorials   37
Behavioral Patterns


           Strategy           Command                   Observer




            Iterator
                                  State                 Template

   Behavioral Patterns: concerned with how classes and objects
               interact and distribute responsibility
2/7/2012                     Design Pattern Tutorials              38
Command Pattern
• Intent: Encapsulate a request as an object, thereby
  letting you parameterize clients with different
  requests, queue or log requests, and support
  undoable operations.
• Use the Command pattern when you want to:
      – parameterize objects by an action to perform, as
        MenuItem objects did above.
      – specify, queue, and execute requests at different times.
      – support undo. The Command's Execute operation can
        store state for reversing its effects in the command itself.
      – support logging changes so that they can be reapplied in
        case of a system crash.
      – structure a system around high-level operations built on
        primitives operations.
2/7/2012                      Design Pattern Tutorials                 39
Command Pattern (cont.)




2/7/2012           Design Pattern Tutorials   40
Command Pattern (cont.)
• Notes:
      – Also Known As Action, Transaction
      – In practice, it is not uncommon for “smart”
        Command objects to implement the request
        themselves rather than delegating to a receiver.
      – Commands may also be used to implement
        logging and transactional systems.



2/7/2012                 Design Pattern Tutorials          41
Iterator Pattern
• Intent: Provide a way to access the elements of an
  aggregate object sequentially without exposing its
  underlying representation.
• Use the Iterator pattern:
      – 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).
2/7/2012                   Design Pattern Tutorials               42
Iterator Pattern (cont.)




2/7/2012           Design Pattern Tutorials   43
Iterator Pattern (cont.)
• Notes:
      – Also known as Cursor
      – When using an Iterator, we relieve the aggregate
        of the responsibility of supporting operations for
        traversing its data.
      – An Iterator provides a common interface for
        traversing the items of an aggregate, allowing you
        to use polymorphism when writing code that
        makes use of the items of the aggregate

2/7/2012                 Design Pattern Tutorials        44
Template Pattern
• Intent: define the skeleton of an algorithm in an
  operation, deferring some steps to subclasses. Template
  Method lets subclasses redefine certain steps of an
  algorithm without changing the algorithm's structure.
• The Template Method pattern should be used:
      – to implement the invariant parts of an algorithm once and leave
        it up to subclasses to implement the behavior that can vary.
      – when common behavior among subclasses should be factored
        and localized in a common class to avoid code duplication.
      – to control subclasses extensions. You can define a template
        method that calls "hook" operations (see Consequences) at
        specific points, thereby permitting extensions only at those
        points.
2/7/2012                      Design Pattern Tutorials                45
Template Pattern (cont.)




2/7/2012           Design Pattern Tutorials   46
Template Pattern
• Notes:
      – Hooks are methods that do nothing or default
        behavior in the abstract class, but may be overridden
        in the subclass
      – To prevent subclasses from changing the algorithm in
        the template method, declare the template method
        as final
      – The Strategy and Template Method Patterns both
        encapsulate algorithms, one by inheritance and one
        by composition
      – The Factory Method is a specialization of Template
        Method

2/7/2012                   Design Pattern Tutorials             47
Observer Pattern
• Intent: define a one-to-many dependency between objects so
  that when one object changes state, all its dependents are
  notified and updated automatically.
• Use the Observer pattern in any of the following situations:
      – When an abstraction has two aspects, one dependent on the other.
        Encapsulating these aspects in separate objects lets you vary and
        reuse them independently.
      – When a change to one object requires changing others, and you don't
        know how many objects need to be changed.
      – When an object should be able to notify other objects without making
        assumptions about who these objects are. In other words, you don't
        want these objects tightly coupled.


2/7/2012                        Design Pattern Tutorials                   48
Observer Pattern (cont.)




2/7/2012           Design Pattern Tutorials   49
Observer Pattern (cont.)
• Notes:
      – Also known as Dependents, Publish-Subscribe
      – You can push or pull data from the Observable
        when using the pattern
      – Don’t depend on a specific order of notification
        for your Observers.
      – Java has several implementations of the Observer
        Pattern, including the general purpose
        java.util.Observable

2/7/2012                 Design Pattern Tutorials          50
Strategy Pattern
• Intent: define a family of algorithms, encapsulate
  each one, and make them interchangeable. Strategy
  lets the algorithm vary independently from clients
  that use it.
• Also known as Policy
• Use the Strategy pattern when:
      – many related classes differ only in their behavior.
         Strategies provide a way to configure a class with one of
         many behaviors.
      – you need different variants of an algorithm.
      – an algorithm uses data that clients shouldn't know about.
         Use the Strategy pattern to avoid exposing complex,
         algorithm-specific data structures.
      – Instead of many conditionals, move related conditional
2/7/2012 branches into their own Pattern Tutorials class.
                              Design Strategy                      51
Strategy Pattern (cont.)




2/7/2012           Design Pattern Tutorials   52
State Pattern
• Intent: allow an object to alter its behavior when its
  internal state changes. The object will appear to change
  its class.
• Use the State pattern in either of the following cases:
      – An object's behavior depends on its state, and it must change its
        behavior at run-time depending on that state.
      – Operations have large, multipart conditional statements that
        depend on the object's state. This state is usually represented
        by one or more enumerated constants. Often, several
        operations will contain this same conditional structure. The
        State pattern puts each branch of the conditional in a separate
        class. This lets you treat the object's state as an object in its own
        right that can vary independently from other objects.

2/7/2012                        Design Pattern Tutorials                   53
State Pattern (cont.)




2/7/2012          Design Pattern Tutorials   54
State Pattern
• Notes:
      – Also known as Objects for States
      – The Context gets its behavior by delegating to the
        current state object is composed with.
      – The State and Strategy Patterns have the same
        class diagram, but they differ in intent.
      – Using the State Pattern will typically result in a
        greater number of classes in your design
      – State classes may be shared among Context
        instances

2/7/2012                 Design Pattern Tutorials            55
Content
           Intro to Design Patterns

             Creational Patterns (A)

              Structural Patterns (B)

             Behavioral Patterns (C)

           Other stuffs and conclusion
2/7/2012                Design Pattern Tutorials   56
Pattern of pattern
• Pattern are often used together and combined
  within the same design solution
• Compound pattern combines two or more
  patterns into a solution that solves a recurring
  or general problem
• The Model View Controller Pattern (MVC) is a
  compound pattern consisting of the Observer,
  Strategy and Composite patterns.

2/7/2012            Design Pattern Tutorials     57
MVC Patterns




2/7/2012      Design Pattern Tutorials   58
MVC Patterns (cont.)




2/7/2012         Design Pattern Tutorials   59
MVC Patterns (cont.)




2/7/2012         Design Pattern Tutorials   60
MVC Patterns (cont.)




2/7/2012         Design Pattern Tutorials   61
Other Design Patterns
    •      Prototype (A)                    •     Interpreter (C)
    •      Builder (A)                      •     Mediator (C)
    •      Bridge (B)                       •     Memento (C)
    •      Flyweight (B)                    •     Visitor (C)
                                            •     Chain of responsibility (C)

    Look up them more in the Head First
    Design Pattern book for more details!


2/7/2012                   Design Pattern Tutorials                      62
Test your
understanding!
Match each pattern
with its description




2/7/2012               Design Pattern Tutorials   63
Conclusion
    Purpose    Design Pattern                    Aspect(s) That Can Vary

Creational    Abstract Factory families of product objects

              Factory Method     subclass of object that is instantiated

              Singleton          the sole instance of a class

Structural    Adapter            interface to an object

              Composite          structure and composition of an object

              Decorator          responsibilities of an object without
                                 subclassing

              Facade             interface to a subsystem

              Proxy              how an object is accessed; its location
2/7/2012                    Design Pattern Tutorials                       64
Conclusion (cont.)
    Purpose    Design Pattern                    Aspect(s) That Can Vary

              Command            when and how a request is fulfilled

              Iterator           how an aggregate's elements are accessed,
                                 traversed
              Observer           number of objects that depend on another
                                 object; how the dependent objects stay up
Behavioral                       to date
              State              states of an object

              Strategy           an algorithm

              Template           steps of an algorithm
              Method

2/7/2012                    Design Pattern Tutorials                         65
Conclusion (cont.)
• Design Patterns (DP) aren’t set in stone, adapt
  and tweak them to meet your needs
• Always use the simplest solution that meets
  your needs, even if it doesn’t include a pattern
• Study DP catalogs to familiarize yourself with
  patterns and the relationship among them
• Most patterns you encounter will be adaptations
  of existing patterns, not new pattern

2/7/2012            Design Pattern Tutorials         66
References
• Head First Design Patterns – by Elisabeth
  Freeman, Eric Freeman, Bert Bates, Kathy
  Sierra, Elisabeth Robson - O'Reilly Media
  (2004)
• Design Patterns: Elements of Reusable
  Object-Oriented Software – by Gang of Four -
  Addison-Wesley Professional (1994)


2/7/2012           Design Pattern Tutorials   67
The End of Design Patterns Tutorials
   THANKS FOR LISTENING
    Editor: Nguyễn Đức Minh Khôi
    @Feb 2012, HCMC University of Technology
    Email: nguyenducminhkhoi@gmail.com
2/7/2012                 Design Pattern Tutorials   68
Ad

Recommended

Let us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Gof design patterns
Gof design patterns
Srikanth R Vaka
 
Software Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Introduction to Design Pattern
Introduction to Design Pattern
Sanae BEKKAR
 
Design patterns ppt
Design patterns ppt
Aman Jain
 
unit 3 Design 1
unit 3 Design 1
TharuniDiddekunta
 
Design Patterns
Design Patterns
Anuja Arosha
 
Software Development Life Cycle (SDLC )
Software Development Life Cycle (SDLC )
eshtiyak
 
Domain model
Domain model
Eagle Eyes
 
Introduction to design patterns
Introduction to design patterns
Amit Kabra
 
Design pattern & categories
Design pattern & categories
Himanshu
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation - Chetan Gole
Chetan Gole
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
APU
 
Design Patterns - General Introduction
Design Patterns - General Introduction
Asma CHERIF
 
Software Design Patterns
Software Design Patterns
Pankhuree Srivastava
 
Design patterns
Design patterns
Elyes Mejri
 
Composite pattern
Composite pattern
Shakil Ahmed
 
Analysis modeling in software engineering
Analysis modeling in software engineering
MuhammadTalha436
 
Design pattern-presentation
Design pattern-presentation
Rana Muhammad Asif
 
Design patterns
Design patterns
abhisheksagi
 
Feature Driven Development
Feature Driven Development
dcsunu
 
An Introduction to Software Architecture
An Introduction to Software Architecture
RahimLotfi
 
ASP.NET Web form
ASP.NET Web form
Md. Mahedee Hasan
 
Android Services
Android Services
Ahsanul Karim
 
Web Engineering
Web Engineering
Muhammad Muzammal
 
The Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1
Shahzad
 
Software architecture
Software architecture
nazn
 
Training python (new Updated)
Training python (new Updated)
University of Technology
 
01 J2EE patrones
01 J2EE patrones
juani ruiz
 

More Related Content

What's hot (20)

Domain model
Domain model
Eagle Eyes
 
Introduction to design patterns
Introduction to design patterns
Amit Kabra
 
Design pattern & categories
Design pattern & categories
Himanshu
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation - Chetan Gole
Chetan Gole
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
APU
 
Design Patterns - General Introduction
Design Patterns - General Introduction
Asma CHERIF
 
Software Design Patterns
Software Design Patterns
Pankhuree Srivastava
 
Design patterns
Design patterns
Elyes Mejri
 
Composite pattern
Composite pattern
Shakil Ahmed
 
Analysis modeling in software engineering
Analysis modeling in software engineering
MuhammadTalha436
 
Design pattern-presentation
Design pattern-presentation
Rana Muhammad Asif
 
Design patterns
Design patterns
abhisheksagi
 
Feature Driven Development
Feature Driven Development
dcsunu
 
An Introduction to Software Architecture
An Introduction to Software Architecture
RahimLotfi
 
ASP.NET Web form
ASP.NET Web form
Md. Mahedee Hasan
 
Android Services
Android Services
Ahsanul Karim
 
Web Engineering
Web Engineering
Muhammad Muzammal
 
The Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1
Shahzad
 
Software architecture
Software architecture
nazn
 
Introduction to design patterns
Introduction to design patterns
Amit Kabra
 
Design pattern & categories
Design pattern & categories
Himanshu
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation - Chetan Gole
Chetan Gole
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
APU
 
Design Patterns - General Introduction
Design Patterns - General Introduction
Asma CHERIF
 
Analysis modeling in software engineering
Analysis modeling in software engineering
MuhammadTalha436
 
Feature Driven Development
Feature Driven Development
dcsunu
 
An Introduction to Software Architecture
An Introduction to Software Architecture
RahimLotfi
 
The Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1
Shahzad
 
Software architecture
Software architecture
nazn
 

Viewers also liked (20)

Training python (new Updated)
Training python (new Updated)
University of Technology
 
01 J2EE patrones
01 J2EE patrones
juani ruiz
 
Pattern making
Pattern making
13023901-016
 
Design patterns
Design patterns
Prawesh Shrestha
 
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Imr Hung
 
Introduction to WEB HTML, CSS
Introduction to WEB HTML, CSS
University of Technology
 
Training android
Training android
University of Technology
 
Software Development Process Seminar at HUI
Software Development Process Seminar at HUI
KMS Technology
 
Training Google Drive and Hangouts.pptx
Training Google Drive and Hangouts.pptx
University of Technology
 
An Introduction of Apache Hadoop
An Introduction of Apache Hadoop
KMS Technology
 
Pbc day-01-introduction
Pbc day-01-introduction
Khánh Nguyễn
 
Git Using - pythonvietnam.info
Git Using - pythonvietnam.info
Khánh Nguyễn
 
Training javascript 2012 hcmut
Training javascript 2012 hcmut
University of Technology
 
Python Beginner Class day-07-08-module
Python Beginner Class day-07-08-module
Khánh Nguyễn
 
Bai 1 pythonvietnam.info
Bai 1 pythonvietnam.info
Khánh Nguyễn
 
Python Beginner Class day-03-flow
Python Beginner Class day-03-flow
Khánh Nguyễn
 
Slide Python Bai 2 pythonvietnam.info
Slide Python Bai 2 pythonvietnam.info
Khánh Nguyễn
 
Python Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterations
Khánh Nguyễn
 
Am hoc kien truc
Am hoc kien truc
Dang Lam
 
Git Version Control System
Git Version Control System
KMS Technology
 
01 J2EE patrones
01 J2EE patrones
juani ruiz
 
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Imr Hung
 
Software Development Process Seminar at HUI
Software Development Process Seminar at HUI
KMS Technology
 
An Introduction of Apache Hadoop
An Introduction of Apache Hadoop
KMS Technology
 
Git Using - pythonvietnam.info
Git Using - pythonvietnam.info
Khánh Nguyễn
 
Python Beginner Class day-07-08-module
Python Beginner Class day-07-08-module
Khánh Nguyễn
 
Bai 1 pythonvietnam.info
Bai 1 pythonvietnam.info
Khánh Nguyễn
 
Python Beginner Class day-03-flow
Python Beginner Class day-03-flow
Khánh Nguyễn
 
Slide Python Bai 2 pythonvietnam.info
Slide Python Bai 2 pythonvietnam.info
Khánh Nguyễn
 
Python Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterations
Khánh Nguyễn
 
Am hoc kien truc
Am hoc kien truc
Dang Lam
 
Git Version Control System
Git Version Control System
KMS Technology
 
Ad

Similar to Design patterns tutorials (20)

Lecture-7.pptx software design and Arthitechure
Lecture-7.pptx software design and Arthitechure
MuhammadAbubakar114879
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
stanbridge
 
Design Pattern - Introduction
Design Pattern - Introduction
Mudasir Qazi
 
Design patterns
Design patterns
Majid Qafouri
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
JS Design patterns in Web technologies including oop techniques.pptx
JS Design patterns in Web technologies including oop techniques.pptx
husnainali397602
 
Creational Design Patterns.pptx
Creational Design Patterns.pptx
Sachin Patidar
 
Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)
APU
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural Patterns
Sergey Aganezov
 
Design Principles to design Patterns
Design Principles to design Patterns
Faizan Haider
 
Daniel leon design principles in the functional world
Daniel leon design principles in the functional world
Codecamp Romania
 
Decorator design pattern
Decorator design pattern
Neelima Sanagavarapu
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven Design
Irwansyah Irwansyah
 
Decorator Pattern
Decorator Pattern
Dimuthu Anuraj
 
OOPSDesign PPT ( introduction to opps and design (
OOPSDesign PPT ( introduction to opps and design (
bhfcvh531
 
12266422.ppt
12266422.ppt
CSEC5
 
Design pattern in android
Design pattern in android
Jay Kumarr
 
Cse 6007 fall2012
Cse 6007 fall2012
rhrashel
 
Contrib First
Contrib First
Mediacurrent
 
Design Patterns .Net
Design Patterns .Net
Hariom Shah
 
Lecture-7.pptx software design and Arthitechure
Lecture-7.pptx software design and Arthitechure
MuhammadAbubakar114879
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
stanbridge
 
Design Pattern - Introduction
Design Pattern - Introduction
Mudasir Qazi
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
JS Design patterns in Web technologies including oop techniques.pptx
JS Design patterns in Web technologies including oop techniques.pptx
husnainali397602
 
Creational Design Patterns.pptx
Creational Design Patterns.pptx
Sachin Patidar
 
Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)
APU
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural Patterns
Sergey Aganezov
 
Design Principles to design Patterns
Design Principles to design Patterns
Faizan Haider
 
Daniel leon design principles in the functional world
Daniel leon design principles in the functional world
Codecamp Romania
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven Design
Irwansyah Irwansyah
 
OOPSDesign PPT ( introduction to opps and design (
OOPSDesign PPT ( introduction to opps and design (
bhfcvh531
 
12266422.ppt
12266422.ppt
CSEC5
 
Design pattern in android
Design pattern in android
Jay Kumarr
 
Cse 6007 fall2012
Cse 6007 fall2012
rhrashel
 
Design Patterns .Net
Design Patterns .Net
Hariom Shah
 
Ad

More from University of Technology (14)

Phương pháp học đại học
Phương pháp học đại học
University of Technology
 
Basic probability & statistics
Basic probability & statistics
University of Technology
 
Introduction to gsa vietnam
Introduction to gsa vietnam
University of Technology
 
Ubuntu – Linux Useful Commands
Ubuntu – Linux Useful Commands
University of Technology
 
Phuong phap hoc tap on thi 2013
Phuong phap hoc tap on thi 2013
University of Technology
 
Training basic latex
Training basic latex
University of Technology
 
Wordnet Introduction
Wordnet Introduction
University of Technology
 
Python/Django Training
Python/Django Training
University of Technology
 
Gioi thieu truong bk
Gioi thieu truong bk
University of Technology
 
Phương pháp học tập official
Phương pháp học tập official
University of Technology
 
English Writing Skills
English Writing Skills
University of Technology
 
Django - basics
Django - basics
University of Technology
 
Python - the basics
Python - the basics
University of Technology
 
Presentation bkit business
Presentation bkit business
University of Technology
 

Recently uploaded (20)

Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 

Design patterns tutorials

  • 1. Design Patterns Tutorials Editor: Nguyễn Đức Minh Khôi @Feb 2012, HCMC University of Technology Email: [email protected]
  • 2. Content Intro to Design Patterns Creational Patterns (A) Structural Patterns (B) Behavioral Patterns (C) Other stuffs and conclusion 2/7/2012 Design Pattern Tutorials 2
  • 3. Intro to Design Patterns • Object Oriented (OO) basics – Abstraction – Encapsulation – Inheritance – Polymorphism 2/7/2012 Design Pattern Tutorials 3
  • 4. Intro to Design Patterns • OO Principles – Encapsulate what varies – Favor composition over inheritance – Program to interfaces, not implementations – Strive for loosely coupled design between objects and interact – Only talk to your friends 2/7/2012 Design Pattern Tutorials 4
  • 5. Intro to Design Patterns • OO Principles (cont.) – Classes should be open for extension but closed for modification – Depend on abstraction. Do not depend on concrete classes – Don’t call us, we’ll call you – A class should have one reason to change 2/7/2012 Design Pattern Tutorials 5
  • 6. Intro to Design Patterns • OO rules: – A class A extends (inherits) a class B (A: subclass, B: superclass) – An interface extends an interface – A class implements an interface – Inheritance -> IS relationship – Composition -> HAS relationship 2/7/2012 Design Pattern Tutorials 6
  • 7. Intro to Design Patterns • What is Pattern? – Pattern is a solution to a problem in a context – Context: the situation in which the pattern apply – Problem: goal you are trying to achieve in this context (any constraints that occur in that context) – Solution: what you are after – general design that anyone can apply which resolves the goal and set of constraints 2/7/2012 Design Pattern Tutorials 7
  • 8. Intro to Design Patterns List of Design Patterns and their relationship 2/7/2012 Design Pattern Tutorials 8
  • 9. Overview of Patterns 2/7/2012 Design Pattern Tutorials 9
  • 10. Content Intro to Design Patterns Creational Patterns (A) Structural Patterns (B) Behavioral Patterns (C) Other stuffs and conclusion 2/7/2012 Design Pattern Tutorials 10
  • 11. Creational Patterns Singleton Abstract Factory Creational Patterns involve object instantiation and all provide a way to decouple a client from the objects it needs to instantiate 2/7/2012 Design Pattern Tutorials 11
  • 12. Factory Method Pattern • Intent: defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method let a class defer instantiation to subclasses. • Use the Factory Method pattern when: – a class can't anticipate the class of objects it must create. – a class wants its subclasses to specify the objects it creates. – classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate. 2/7/2012 Design Pattern Tutorials 12
  • 13. Factory Method Pattern (cont.) 2/7/2012 Design Pattern Tutorials 13
  • 14. Factory Method Pattern (cont.) • Notes: – Also known as Virtual Constructor – Encapsulate objects creation – Rely on inheritance, object creation is delegated to subclasses with implement the factory method to create objects. – Promote loose coupling by reducing the dependency of your application to concrete classes – Are powerful technique for coding abstraction, not concrete classes 2/7/2012 Design Pattern Tutorials 14
  • 15. Abstract Factory Pattern • Intent: Provides an interface for creating families of related or dependent objects without specifying their concrete classes • Use the Abstract Factory pattern when: – a system should be independent of how its products are created, composed, and represented. – a system should be configured with one of multiple families of products. – a family of related product objects is designed to be used together, and you need to enforce this constraint. – you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations. 2/7/2012 Design Pattern Tutorials 15
  • 16. Abstract Factory Pattern (cont.) 2/7/2012 Design Pattern Tutorials 16
  • 17. Abstract Factory Pattern (cont.) • Notes: – Also known as KIT – Rely on composition, object creation is implemented in methods exposed in the factory interface – Others like Factory Method! 2/7/2012 Design Pattern Tutorials 17
  • 18. Singleton Pattern • Intents: Ensure a class only has one instance, and provide a global point of access to it. • Use the Singleton pattern when – there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. – when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code. – Be careful with multithread! 2/7/2012 Design Pattern Tutorials 18
  • 19. Singleton Pattern (cont.) 2/7/2012 Design Pattern Tutorials 19
  • 20. Content Intro to Design Patterns Creational Patterns (A) Structural Patterns (B) Behavioral Patterns (C) Other stuffs and conclusion 2/7/2012 Design Pattern Tutorials 20
  • 21. Structural Patterns Decorator Adapter Façade Composite Proxy Structural Patterns let you compose classes or objects into larger structures 2/7/2012 Design Pattern Tutorials 21
  • 22. Decorator Pattern • Intent: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. • Use Decorator: – to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects. – for responsibilities that can be withdrawn. – when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing. 2/7/2012 Design Pattern Tutorials 22
  • 23. Decorator Pattern (cont.) 2/7/2012 Design Pattern Tutorials 23
  • 24. Decorator Pattern (cont.) • Notes: – Also known as Wrapper – Decorator classes are the same type as the components they decorate, either through inheritance or interface implementation. – You can wrap a component with any number of decorators. – Decorators can result in many small objects in our design, and overuse can be complex. – Decorators are typically transparent to the client of the component 2/7/2012 Design Pattern Tutorials 24
  • 25. Adapter Pattern • Intent: convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. • Use the Adapter pattern when: – you want to use an existing class, and its interface does not match the one you need. – you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces. – (object adapter only) you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class. 2/7/2012 Design Pattern Tutorials 25
  • 26. Adapter Pattern (cont.) 2/7/2012 Design Pattern Tutorials 26
  • 27. Adapter Pattern (cont.) • Notes: – Implementing an adapter may require little work or a great deal of work depending on the size and complexity of the target interface – Adapter Pattern has 2 forms: object and class adapters. Class adapters require multiple inheritance – Adapter wraps an object to change its interface, a decorator wraps an object to add new behaviors and responsibilities 2/7/2012 Design Pattern Tutorials 27
  • 28. Facade Pattern • Intent: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher- level interface that makes the subsystem easier to use. • Use the Facade pattern when: – you want to provide a simple interface to a complex subsystem. – there are many dependencies between clients and the implementation classes of an abstraction. you want to layer your subsystems. – Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them communicate with each other solely through their facades. 2/7/2012 Design Pattern Tutorials 28
  • 29. Facade Pattern (cont.) 2/7/2012 Design Pattern Tutorials 29
  • 30. Facade Pattern (cont.) • Notes: – A façade decouple a client from complex system – Implementing a façade requires that we compose the façade with its subsystem and use delegation to perform the work of the façade. – You can implement more than one façade for a subsystem. – A façade wraps a set of objects to simplify 2/7/2012 Design Pattern Tutorials 30
  • 31. Composite Pattern • Intent: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. • Use the Composite pattern when: – you want to represent part-whole hierarchies of objects. – you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly. 2/7/2012 Design Pattern Tutorials 31
  • 32. Composite Pattern (cont.) 2/7/2012 Design Pattern Tutorials 32
  • 33. Composite Pattern (cont.) • Notes: – A composition provides a structure to hold both individual (leaf nodes) objects and composites – There are many design tradeoffs in implementing Composite. You need to balance transparency and safety with your needs 2/7/2012 Design Pattern Tutorials 33
  • 34. Proxy Pattern • Intent: Provide a surrogate or placeholder for another object to control access to it. • Use the Composite pattern when: – you want to represent part-whole hierarchies of objects. – you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly. 2/7/2012 Design Pattern Tutorials 34
  • 35. Proxy Pattern (cont.) 2/7/2012 Design Pattern Tutorials 35
  • 36. Proxy Pattern (cont.) • Notes: – Also known as Surrogate – The Decorator Pattern adds behavior to an object, while a Proxy controls access – Like any wrapper, proxies will increase the number of classes and objects in your designs – Types of proxy: Remote proxy, virtual proxy, protection proxy 2/7/2012 Design Pattern Tutorials 36
  • 37. Content Intro to Design Patterns Creational Patterns (A) Structural Patterns (B) Behavioral Patterns (C) Other stuffs and conclusion 2/7/2012 Design Pattern Tutorials 37
  • 38. Behavioral Patterns Strategy Command Observer Iterator State Template Behavioral Patterns: concerned with how classes and objects interact and distribute responsibility 2/7/2012 Design Pattern Tutorials 38
  • 39. Command Pattern • Intent: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. • Use the Command pattern when you want to: – parameterize objects by an action to perform, as MenuItem objects did above. – specify, queue, and execute requests at different times. – support undo. The Command's Execute operation can store state for reversing its effects in the command itself. – support logging changes so that they can be reapplied in case of a system crash. – structure a system around high-level operations built on primitives operations. 2/7/2012 Design Pattern Tutorials 39
  • 40. Command Pattern (cont.) 2/7/2012 Design Pattern Tutorials 40
  • 41. Command Pattern (cont.) • Notes: – Also Known As Action, Transaction – In practice, it is not uncommon for “smart” Command objects to implement the request themselves rather than delegating to a receiver. – Commands may also be used to implement logging and transactional systems. 2/7/2012 Design Pattern Tutorials 41
  • 42. Iterator Pattern • Intent: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. • Use the Iterator pattern: – 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). 2/7/2012 Design Pattern Tutorials 42
  • 43. Iterator Pattern (cont.) 2/7/2012 Design Pattern Tutorials 43
  • 44. Iterator Pattern (cont.) • Notes: – Also known as Cursor – When using an Iterator, we relieve the aggregate of the responsibility of supporting operations for traversing its data. – An Iterator provides a common interface for traversing the items of an aggregate, allowing you to use polymorphism when writing code that makes use of the items of the aggregate 2/7/2012 Design Pattern Tutorials 44
  • 45. Template Pattern • Intent: define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. • The Template Method pattern should be used: – to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary. – when common behavior among subclasses should be factored and localized in a common class to avoid code duplication. – to control subclasses extensions. You can define a template method that calls "hook" operations (see Consequences) at specific points, thereby permitting extensions only at those points. 2/7/2012 Design Pattern Tutorials 45
  • 46. Template Pattern (cont.) 2/7/2012 Design Pattern Tutorials 46
  • 47. Template Pattern • Notes: – Hooks are methods that do nothing or default behavior in the abstract class, but may be overridden in the subclass – To prevent subclasses from changing the algorithm in the template method, declare the template method as final – The Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition – The Factory Method is a specialization of Template Method 2/7/2012 Design Pattern Tutorials 47
  • 48. Observer Pattern • Intent: define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. • Use the Observer pattern in any of the following situations: – When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. – When a change to one object requires changing others, and you don't know how many objects need to be changed. – When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled. 2/7/2012 Design Pattern Tutorials 48
  • 49. Observer Pattern (cont.) 2/7/2012 Design Pattern Tutorials 49
  • 50. Observer Pattern (cont.) • Notes: – Also known as Dependents, Publish-Subscribe – You can push or pull data from the Observable when using the pattern – Don’t depend on a specific order of notification for your Observers. – Java has several implementations of the Observer Pattern, including the general purpose java.util.Observable 2/7/2012 Design Pattern Tutorials 50
  • 51. Strategy Pattern • Intent: define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. • Also known as Policy • Use the Strategy pattern when: – many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors. – you need different variants of an algorithm. – an algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures. – Instead of many conditionals, move related conditional 2/7/2012 branches into their own Pattern Tutorials class. Design Strategy 51
  • 52. Strategy Pattern (cont.) 2/7/2012 Design Pattern Tutorials 52
  • 53. State Pattern • Intent: allow an object to alter its behavior when its internal state changes. The object will appear to change its class. • Use the State pattern in either of the following cases: – An object's behavior depends on its state, and it must change its behavior at run-time depending on that state. – Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects. 2/7/2012 Design Pattern Tutorials 53
  • 54. State Pattern (cont.) 2/7/2012 Design Pattern Tutorials 54
  • 55. State Pattern • Notes: – Also known as Objects for States – The Context gets its behavior by delegating to the current state object is composed with. – The State and Strategy Patterns have the same class diagram, but they differ in intent. – Using the State Pattern will typically result in a greater number of classes in your design – State classes may be shared among Context instances 2/7/2012 Design Pattern Tutorials 55
  • 56. Content Intro to Design Patterns Creational Patterns (A) Structural Patterns (B) Behavioral Patterns (C) Other stuffs and conclusion 2/7/2012 Design Pattern Tutorials 56
  • 57. Pattern of pattern • Pattern are often used together and combined within the same design solution • Compound pattern combines two or more patterns into a solution that solves a recurring or general problem • The Model View Controller Pattern (MVC) is a compound pattern consisting of the Observer, Strategy and Composite patterns. 2/7/2012 Design Pattern Tutorials 57
  • 58. MVC Patterns 2/7/2012 Design Pattern Tutorials 58
  • 59. MVC Patterns (cont.) 2/7/2012 Design Pattern Tutorials 59
  • 60. MVC Patterns (cont.) 2/7/2012 Design Pattern Tutorials 60
  • 61. MVC Patterns (cont.) 2/7/2012 Design Pattern Tutorials 61
  • 62. Other Design Patterns • Prototype (A) • Interpreter (C) • Builder (A) • Mediator (C) • Bridge (B) • Memento (C) • Flyweight (B) • Visitor (C) • Chain of responsibility (C) Look up them more in the Head First Design Pattern book for more details! 2/7/2012 Design Pattern Tutorials 62
  • 63. Test your understanding! Match each pattern with its description 2/7/2012 Design Pattern Tutorials 63
  • 64. Conclusion Purpose Design Pattern Aspect(s) That Can Vary Creational Abstract Factory families of product objects Factory Method subclass of object that is instantiated Singleton the sole instance of a class Structural Adapter interface to an object Composite structure and composition of an object Decorator responsibilities of an object without subclassing Facade interface to a subsystem Proxy how an object is accessed; its location 2/7/2012 Design Pattern Tutorials 64
  • 65. Conclusion (cont.) Purpose Design Pattern Aspect(s) That Can Vary Command when and how a request is fulfilled Iterator how an aggregate's elements are accessed, traversed Observer number of objects that depend on another object; how the dependent objects stay up Behavioral to date State states of an object Strategy an algorithm Template steps of an algorithm Method 2/7/2012 Design Pattern Tutorials 65
  • 66. Conclusion (cont.) • Design Patterns (DP) aren’t set in stone, adapt and tweak them to meet your needs • Always use the simplest solution that meets your needs, even if it doesn’t include a pattern • Study DP catalogs to familiarize yourself with patterns and the relationship among them • Most patterns you encounter will be adaptations of existing patterns, not new pattern 2/7/2012 Design Pattern Tutorials 66
  • 67. References • Head First Design Patterns – by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson - O'Reilly Media (2004) • Design Patterns: Elements of Reusable Object-Oriented Software – by Gang of Four - Addison-Wesley Professional (1994) 2/7/2012 Design Pattern Tutorials 67
  • 68. The End of Design Patterns Tutorials THANKS FOR LISTENING Editor: Nguyễn Đức Minh Khôi @Feb 2012, HCMC University of Technology Email: [email protected] 2/7/2012 Design Pattern Tutorials 68