SlideShare ist ein Scribd-Unternehmen logo
1 von 68
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Types of UML diagrams
Types of UML diagramsTypes of UML diagrams
Types of UML diagrams
 
UML and Software Modeling Tools.pptx
UML and Software Modeling Tools.pptxUML and Software Modeling Tools.pptx
UML and Software Modeling Tools.pptx
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Decorator Pattern
Decorator PatternDecorator Pattern
Decorator Pattern
 
UML Diagrams
UML DiagramsUML Diagrams
UML Diagrams
 
uml reference package_diagram
uml reference package_diagramuml reference package_diagram
uml reference package_diagram
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Uml Presentation
Uml PresentationUml Presentation
Uml Presentation
 
Facade Pattern
Facade PatternFacade Pattern
Facade Pattern
 
Domain object model
Domain object modelDomain object model
Domain object model
 
What is design pattern
What is design patternWhat is design pattern
What is design pattern
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Uml - An Overview
Uml - An OverviewUml - An Overview
Uml - An Overview
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 

Andere mochten auch

01 J2EE patrones
01 J2EE patrones01 J2EE patrones
01 J2EE patronesjuani 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 NamMộ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 NamImr Hung
 
Software Development Process Seminar at HUI
Software Development Process Seminar at HUISoftware Development Process Seminar at HUI
Software Development Process Seminar at HUIKMS Technology
 
An Introduction of Apache Hadoop
An Introduction of Apache HadoopAn Introduction of Apache Hadoop
An Introduction of Apache HadoopKMS Technology
 
Git Using - pythonvietnam.info
Git Using - pythonvietnam.infoGit Using - pythonvietnam.info
Git Using - pythonvietnam.infoKhánh Nguyễn
 
Python Beginner Class day-07-08-module
Python Beginner Class day-07-08-modulePython Beginner Class day-07-08-module
Python Beginner Class day-07-08-moduleKhánh Nguyễn
 
Bai 1 pythonvietnam.info
Bai 1   pythonvietnam.infoBai 1   pythonvietnam.info
Bai 1 pythonvietnam.infoKhánh Nguyễn
 
Python Beginner Class day-03-flow
Python Beginner Class day-03-flowPython Beginner Class day-03-flow
Python Beginner Class day-03-flowKhánh Nguyễn
 
Slide Python Bai 2 pythonvietnam.info
Slide Python Bai 2   pythonvietnam.infoSlide Python Bai 2   pythonvietnam.info
Slide Python Bai 2 pythonvietnam.infoKhánh Nguyễn
 
Python Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterationsPython Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterationsKhánh Nguyễn
 
Am hoc kien truc
Am hoc kien trucAm hoc kien truc
Am hoc kien trucDang Lam
 
Git Version Control System
Git Version Control SystemGit Version Control System
Git Version Control SystemKMS Technology
 

Andere mochten auch (20)

Training python (new Updated)
Training python (new Updated)Training python (new Updated)
Training python (new Updated)
 
01 J2EE patrones
01 J2EE patrones01 J2EE patrones
01 J2EE patrones
 
Pattern making
Pattern makingPattern making
Pattern making
 
Design patterns
Design patternsDesign patterns
Design patterns
 
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 NamMộ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
 
Introduction to WEB HTML, CSS
Introduction to WEB HTML, CSSIntroduction to WEB HTML, CSS
Introduction to WEB HTML, CSS
 
Training android
Training androidTraining android
Training android
 
Software Development Process Seminar at HUI
Software Development Process Seminar at HUISoftware Development Process Seminar at HUI
Software Development Process Seminar at HUI
 
Training Google Drive and Hangouts.pptx
Training Google Drive and Hangouts.pptxTraining Google Drive and Hangouts.pptx
Training Google Drive and Hangouts.pptx
 
An Introduction of Apache Hadoop
An Introduction of Apache HadoopAn Introduction of Apache Hadoop
An Introduction of Apache Hadoop
 
Pbc day-01-introduction
Pbc day-01-introductionPbc day-01-introduction
Pbc day-01-introduction
 
Git Using - pythonvietnam.info
Git Using - pythonvietnam.infoGit Using - pythonvietnam.info
Git Using - pythonvietnam.info
 
Training javascript 2012 hcmut
Training javascript 2012 hcmutTraining javascript 2012 hcmut
Training javascript 2012 hcmut
 
Python Beginner Class day-07-08-module
Python Beginner Class day-07-08-modulePython Beginner Class day-07-08-module
Python Beginner Class day-07-08-module
 
Bai 1 pythonvietnam.info
Bai 1   pythonvietnam.infoBai 1   pythonvietnam.info
Bai 1 pythonvietnam.info
 
Python Beginner Class day-03-flow
Python Beginner Class day-03-flowPython Beginner Class day-03-flow
Python Beginner Class day-03-flow
 
Slide Python Bai 2 pythonvietnam.info
Slide Python Bai 2   pythonvietnam.infoSlide Python Bai 2   pythonvietnam.info
Slide Python Bai 2 pythonvietnam.info
 
Python Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterationsPython Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterations
 
Am hoc kien truc
Am hoc kien trucAm hoc kien truc
Am hoc kien truc
 
Git Version Control System
Git Version Control SystemGit Version Control System
Git Version Control System
 

Ähnlich wie Design patterns tutorials

Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)stanbridge
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - IntroductionMudasir Qazi
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptxSachin Patidar
 
Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)APU
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSergey Aganezov
 
Design Principles to design Patterns
Design Principles to design PatternsDesign Principles to design Patterns
Design Principles to design PatternsFaizan Haider
 
Daniel leon design principles in the functional world
Daniel leon   design principles in the functional worldDaniel leon   design principles in the functional world
Daniel leon design principles in the functional worldCodecamp Romania
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignIrwansyah Irwansyah
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.pptCSEC5
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in androidJay Kumarr
 
Cse 6007 fall2012
Cse 6007 fall2012Cse 6007 fall2012
Cse 6007 fall2012rhrashel
 
Design Patterns .Net
Design Patterns .NetDesign Patterns .Net
Design Patterns .NetHariom Shah
 
Dependency injection via annotations v1.0
Dependency injection via annotations v1.0Dependency injection via annotations v1.0
Dependency injection via annotations v1.0Jerry Kurian
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1Tom Chen
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfB.T.L.I.T
 

Ähnlich wie Design patterns tutorials (20)

Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - Introduction
 
Design patterns
Design patternsDesign patterns
Design patterns
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural Patterns
 
Design Principles to design Patterns
Design Principles to design PatternsDesign Principles to design Patterns
Design Principles to design Patterns
 
Daniel leon design principles in the functional world
Daniel leon   design principles in the functional worldDaniel leon   design principles in the functional world
Daniel leon design principles in the functional world
 
Decorator design pattern
Decorator design patternDecorator design pattern
Decorator design pattern
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven Design
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.ppt
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in android
 
Cse 6007 fall2012
Cse 6007 fall2012Cse 6007 fall2012
Cse 6007 fall2012
 
Contrib First
Contrib FirstContrib First
Contrib First
 
Design Patterns .Net
Design Patterns .NetDesign Patterns .Net
Design Patterns .Net
 
Dependency injection via annotations v1.0
Dependency injection via annotations v1.0Dependency injection via annotations v1.0
Dependency injection via annotations v1.0
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdf
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 

Mehr von University of Technology (14)

Phương pháp học đại học
Phương pháp học đại họcPhương pháp học đại học
Phương pháp học đại học
 
Basic probability & statistics
Basic probability & statisticsBasic probability & statistics
Basic probability & statistics
 
Introduction to gsa vietnam
Introduction to gsa vietnamIntroduction to gsa vietnam
Introduction to gsa vietnam
 
Ubuntu – Linux Useful Commands
Ubuntu – Linux Useful CommandsUbuntu – Linux Useful Commands
Ubuntu – Linux Useful Commands
 
Phuong phap hoc tap on thi 2013
Phuong phap hoc tap on thi 2013Phuong phap hoc tap on thi 2013
Phuong phap hoc tap on thi 2013
 
Training basic latex
Training basic latexTraining basic latex
Training basic latex
 
Wordnet Introduction
Wordnet IntroductionWordnet Introduction
Wordnet Introduction
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
 
Gioi thieu truong bk
Gioi thieu truong bkGioi thieu truong bk
Gioi thieu truong bk
 
Phương pháp học tập official
Phương pháp học tập officialPhương pháp học tập official
Phương pháp học tập official
 
English Writing Skills
English Writing SkillsEnglish Writing Skills
English Writing Skills
 
Django - basics
Django - basicsDjango - basics
Django - basics
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Presentation bkit business
Presentation bkit businessPresentation bkit business
Presentation bkit business
 

Kürzlich hochgeladen

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dashnarutouzumaki53779
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Kürzlich hochgeladen (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dash
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Design patterns tutorials

  • 1. Design Patterns Tutorials Editor: Nguyễn Đức Minh Khôi @Feb 2012, HCMC University of Technology Email: nguyenducminhkhoi@gmail.com
  • 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: nguyenducminhkhoi@gmail.com 2/7/2012 Design Pattern Tutorials 68