design patterns part1

Download Design Patterns  Part1

If you can't read please download the document

Upload: tom-chen

Post on 07-Aug-2015

35 views

Category:

Technology


1 download

TRANSCRIPT

  1. 1. Design Patterns: Elements of Reusable Object-Oriented Software (Part 1) Tom Chen
  2. 2. Overview Introduction What is Design Pattern? Organizing Design Patterns How to Select a Design Pattern? Design Patterns Part 1 Creational: Factory, Abstract Factory, Singleton Structual: Bridge, Decorator Behavioral: Interpreter, Visitor
  3. 3. What is Design Pattern? "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice"
  4. 4. What is Design Pattern? Four Essential Elements Pattern name A handle used to describe a design problem, its solutions, and consequences in a word or two Problem When to apply the pattern. Solution The elements that make up the design, their relationships, responsibilities, and collaborations Consequences The results and trade-offs of applying the pattern
  5. 5. Priciples of Design Patterns Program to an interface, not an implementation. Polymorphism Favor object composition over class inheritance. Delegation
  6. 6. Organizing Design Patterns Creational Patterns Abstract the instantiation process Structural Patterns How classes and objects are composed to form larger structures Behavioral Patterns Describe algorithms and the assignment of responsibilities between objects Not just patterns of objects or classes but also the patterns of communication between them
  7. 7. Organizing Design Patterns c.1
  8. 8. Creational Patterns Factory Method Intent Define an interface for creating an object, but let subclasses decide which class to instantiate. Motivation A framework for applications that can present multiple documents to user Both classes of application and document are abstract subclass them to realize their application-specific implementations
  9. 9. Creational Patterns Factory Method Application doesn't know which subclass to instantiate. CreateDocument() is the factory method!
  10. 10. Creational Patterns Factory Method Applicability 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.
  11. 11. Factory Method Structure
  12. 12. Factory Method Sample Code
  13. 13. Factory Method Sample Code c.1
  14. 14. Factory Method Sample Code c.2
  15. 15. Factory Method Consequences Eliminate the need to bind application-specific classes into your code Potential Disadv. : clients might have to subclass the Creator class just to create a particular ConcreteProduct object
  16. 16. Creational Patterns Abstract Factory Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Motivation A UI toolkit that supports multiple look-and-feel standards To be portable, should not hard-code widgets for a particular look and feel
  17. 17. Creational Patterns Abstract Factory This is the Abstract Factory!
  18. 18. Abstract Factory Applicability 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 Only want to reveal the interface of a class library of products, not the implementations
  19. 19. Abstract Factory Structure
  20. 20. Abstract Factory Sample Code New interface! An abstract factory. Factory Methods are defined!
  21. 21. Pass in abstract factory. Create objects with the factory Usage of the new interface:
  22. 22. Abstract Factory Consequences Isolates concrete classes Makes exchanging product families easy Promotes consistency among products Application use objects from only one family at a time Difficult to support new kinds of products Change the AbstractFactory class and all of its subclasses
  23. 23. Creational Patterns Singleton Intent Ensure a class only has one instance, and provide a global point of access to it. Motivation Important for some classes to have exactly one instance Only one printer spooler, one file system, one window manager... Solution: make the class itself responsible for keeping track of its sole instance Ensure that no other instance can be created Provide a way to access the instance
  24. 24. Singleton Applicability Must be exactly one instance of a class and 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
  25. 25. Singleton Structure
  26. 26. Singleton Sample Code
  27. 27. Singleton Consequences Controlled access to sole instance Reduced name space An improvement over global variables Permits refinement of operations and representation By subclassing Permits a variable number of instances More flexible than class operations (Static member functions)
  28. 28. Structural Patterns Bridge Intent Decouple an abstraction from its implementation so that the two can vary independently. Motivation An abstract class defines the interface and concrete subclasses implement it in different ways. Not always flexible enough Inheritance binds an implementation to the abstraction permanently Difficult to modify, extend, and reuse abstractions and implementations independently
  29. 29. Bridge Motivation c.1 Case: Implement a portable Window abstract Work on both XWindow and IBM's Presentation Manager(PM)
  30. 30. Bridge Motivation c.2
  31. 31. Bridge Applicability Avoid permanent binding between abstraction and implementation EX: Select or switch implementation at run-time Both the abstractions and their implementations should be extensible by subclassing Changes in the implementation of an abstraction should have no impact on clients
  32. 32. Bridge Structure
  33. 33. Bridge Sample Code
  34. 34. Bridge Sample Code c.1
  35. 35. Bridge Consequences Decoupling interface and implementation Even possible for an object to change implementation at run-time Eliminate compile-time dependencies on the implementation Improved extensibility Extend the Abstraction and Implementor hierarchies independently Hiding implementation details from clients
  36. 36. Structural Patterns Decorator Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Motivation Add responsibilities to individual objects, not to an entire class EX: Add properties like borders or behaviors like scrolling to any UI component Inheritance is inflexible
  37. 37. Structural Patterns Decorator
  38. 38. Structural Patterns Decorator DrawScrollbar() Draw() Draw() Draw() DrawBorder()
  39. 39. Decorator Applicability Add responsibilities to individual objects dynamically and transparently For responsibilities that can be withdrawn When extension by subclassing is impractical Produce an explosion of subclasses Class definition may be hidden or unavailable for subclassing
  40. 40. Decorator Structure
  41. 41. Decorator Sample Code
  42. 42. Decorator Sample Code c.1
  43. 43. Decorator Consequences More flexibility than static inheritance Responsibilities can be added and removed at run- time Avoid feature-laden classes high up in the hierarchy Inheritance requires creating a new class for each additional responsibility A decorator and its component aren't identical Lots of little objects Easy to customize but can be hard to learn and debug
  44. 44. Behavioral Patterns Visitor Intent Represent an operation to be performed on the elements of an object structure Define a new operation without changing the classes of the elements on which it operates Motivation 2D CAD System: Simple geometries compose a model Basic functions Save model to file, drawing, dragging, scale ...
  45. 45. Visitor Motivation Difficult to extend the ability of Shape!
  46. 46. Visitor Motivation c.1 Key: Double Dispatch!
  47. 47. Visitor Applicability Perform operations on object structure containig many classes of objects with differing interfaces Avoid polluting classes with distinct and unrelated operations Visitor keep related operations together Classes defining object structure rarely change, but often define new operations Change class need redefining interface to all visitors
  48. 48. Visitor Structure
  49. 49. Visitor Structure c.1
  50. 50. Visitor Sample Code
  51. 51. Visitor Sample Code c.1
  52. 52. Visitor Consequences Visitor makes adding new operations easy Visitor gathers related operations and separates unrelated ones Adding new ConcreteElement classes is hard Corresponding implementation in every ConcreteVisitor class
  53. 53. Visitor Consequences c.1 Visiting across class hierarchies Iterator works for classes of the same parent Visitor works for classes of different parent Accumulating state while visiting elements Breaking encapsulation Must provide public operations that access an element's internal state
  54. 54. Behavioral Patterns Interpreter Intent Given a language, define a representation for its grammar along with an interpreter using the representation to interpret sentences in the language Motivation Search for strings matching a pattern decribed by Regular Expression Search algorithms could interpret a regular expression rather than building custom algorithm
  55. 55. Interpreter Motivation c.1 Suppose the following grammar defines the regular expressions
  56. 56. Interpreter Motivation c.2 Context
  57. 57. Interpreter Motivation c.3 raining & (dogs | cats) * EX: Context = It is raining cats and dogs.
  58. 58. Interpreter Applicability Grammar is simple For complex grammars, the class hierarchy for the grammar becomes large and unmanageable Efficiency is not a critical concern
  59. 59. Interpreter Structure
  60. 60. Interpreter Consequences Easy to change and extend the grammar Implementing the grammar is easy, too Complex grammars are hard to maintain. Adding new ways to interpret expressions (Easier) EX: Support pretty printing or type-checking an expression by defining a new operation Use Visitor to avoid changing grammar classes