Design Patterns Part I Intro  Creational Patterns

Design Patterns Part I Intro Creational Patterns PowerPoint PPT Presentation


  • 216 Views
  • Updated On :
  • Presentation posted in: General

2. What's a pattern?. A pattern is a named abstraction from a concrete form that represents a recurring solution to a particular problem. . 3. Categories of Patterns. Design patterns vary in granularity and level of abstraction.By categorizing patterns, it becomes easier to recognize and learn thempatterns can be categorized by purpose or scopepurpose reflects what the pattern doesscope specifies if the pattern applies to classes or objects.

Related searches for Design Patterns Part I Intro Creational Patterns

Download Presentation

Design Patterns Part I Intro Creational Patterns

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

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


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


1. Design Patterns Part I Intro & Creational Patterns “Patterns are discovered, not invented” Richard Helm

2. 2 What’s a pattern? A pattern is a named abstraction from a concrete form that represents a recurring solution to a particular problem.

3. 3 Categories of Patterns Design patterns vary in granularity and level of abstraction. By categorizing patterns, it becomes easier to recognize and learn them patterns can be categorized by purpose or scope purpose reflects what the pattern does scope specifies if the pattern applies to classes or objects

4. 4 purpose reflects what the pattern does creational -- facilitate object creation structural -- deal with the composition of classes or objects behavioral -- deal with the way objects interact and distribute responsibility

5. 5 scope whether the pattern applies to classes or objects class patterns: deal with relationships between classes or subclasses established through inheritance these relationships are fixed at compile time objects patterns: deal with object relationships that can be changed at runtime

6. 6 other ways to organize patterns some patterns are frequently used with other patterns, for example composite is often used with visitor and/or iterator some patterns are alternatives: Prototype is usually an alternative for Abstract Factory Some patterns are very similar in structure, such as Composite and Decorator

7. 7 How do Design Patterns Solve Design Problems? The meaning of OO is well-known The hard part is decomposing the system into objects to exploit: encapsulation flexibility, extensibility ease of modification performance evolution reusability

8. 8 Finding objects Many objects in the design come from the analysis model But OO designs often end up with classes that have no counterpart in the real world Design Patterns help the modeler to identify less obvious abstractions and the objects that can capture them.

9. 9 Inheritance Inheritance is a mechanism for reuse you can define a new kind of object in terms of the old one you get new implementations almost for free, inheriting most of what you need from an existing class This is only half the story!

10. 10 Program to an interface, not an implementation Inheritance permits defining a family of objects with identical interfaces polymorphism depends on this! all derived classes share the base class interface Subclasses add or override operations, rather than hiding operations All subclasses then respond to requests in the interface of the abstract class

11. 11 Inheritance properly used clients are unaware of types of objects: heuristic 5.12 - “explicit case analysis on the type of an object is usually an error. The designer should use polymorphism”. Riel clients only know about the abstract classes defining the interface. heuristic 5.7: “All base classes should be abstract”. Riel This reduces implementation dependencies program to an interface, not an implementation creational patterns help ensure this rule!

12. 12 Two techniques for reuse inheritance: white box object composition: black box

13. 13 advantage of inheritance for reuse defined statically supported directly by the language: straightforward to use easier to modify implementation being reused

14. 14 disadvantage of inheritance can’t change inherited implementation at run-time parent classes often define part of their subclasses physical representation because inheritance exposes the parent implementation it’s said to “break encapsulation” (GOF p.19, Sny86) change in parent => change in subclass if inherited attribute is inappropriate?

15. 15 object composition: black box reuse objects are accessed solely through their interfaces: no break of encapsulation any object can be replaced by another at runtime: as long as they are the same type favor object composition over class inheritance. GOF p. 20 but inheritance & composition work together!

16. 16 Delegation “a way of making composition as powerful for reuse as inheritance”: GOF, p. 20 [JZ91] Ralph Johnson and Jonathan Zweig, Delegation in C++, JOOP, f(11):22-35, Nov. 91 [Lie86] Henry Lieberman. Using prototypical objects to implement shared behavior in OO systems. OOPSLA, pp 214-223, Nov. ‘86

17. 17 delegation: reuse In delegation, 2 objects handle a request analogous to subclass deferring request to parent in delegation, the receiver passes itself to the delegate to let the delegated operation refer to the receiver!

18. 18 delegating area() to rectangle

19. 19 advantages of delegation can change behaviors at run-time window can become circular at run-time by replacing Rectangle with Circle, (assuming Rectangle & Circle are same type!) There are run-time costs. delegation in patterns: State, Strategy, Visitor, Mediator, Bridge

20. 20 Patterns make design resistant to re-design Robustness to Change Algorithmic dependencies: Template Method, Visitor, Iterator, Builder, Strategy. creating an object by specifying a class explicitly: Abstract Factory, Factory Method, Prototype Dependence on specific operations: Command, chain of responsibility Dependence on object rep or impl: Abstract Factory, Bridge, Proxy tight coupling: Abstract Factory, Command, Facade, Mediator, Observer, Bridge

21. 21 Patterns make design resistant to re-design extending functionality by subclassing: Command, Bridge, Composite, Decorator, Observer, Strategy inability to alter classes conveniently: Visitor, Adapter, Decorator

22. 22 Design Confidence Design Inexperience: “Is my design ok?” Patterns engender confidence used twice & blame the GOF still room for creativity

23. 23 Design Coverage Large portion of design can be covered by patterns Seductively simple to implement most explained in a few pages add no “extra-value” to end-user You still have to write functionality: patterns don’t solve the problem

24. 24 Design Understanding Most people know the patterns If you’re looking at someone’s design & you identify a pattern, you immediately understand much of the design Common design vocabulary “Let’s use a Builder here” Design language beyond language syntax problem oriented language program in rather than into the language

25. 25 Common Problems Getting the “right” pattern Taming over-enthusiasm you “win” if you use the most patterns everything solved by the last pattern you learned

26. 26 How to select a pattern know a basic catalog scan intent section study patterns of like purpose consider a cause of redesign

27. 27 Creational Patterns Chapter 3 of GOF

28. 28 Overview of creational patterns abstract the instantiation process help make a system independent of how its objects are created, composed, represented a class creational pattern uses inheritance to vary the class that’s instantiated an object creational pattern delegates instantiation to another object

29. 29 closely related competitors: either Prototype or Abstract Factory could be used Complementary: Prototype can use Singleton We’ll study 5 together to highlight similarities and differences use a common example: a maze for a computer game

30. 30 Mazes The maze & the game will vary slightly from pattern to pattern Sometimes the game will be simply to find your way of of the maze: the player only has a local view of the maze Sometimes mazes contain problems to solve and dangers to avoid: the player has a map We’ll ignore detail & focus on maze creation

31. 31 Class Diagram for the Maze

32. 32 Common abstract class for all components of the maze

33. 33 The components of the maze Room

34. 34 The components of the maze Wall & Door

35. 35 the Maze

36. Creating the maze

37. This is GOF Maze; we want to play a game!

38. This is GOF Maze; we want to play a game!

39. “Care for a game of GTW!” The Wopper

40. Close to a Composite Pattern, but not quite!

41. This part resembles Composite!

42. Use a creational pattern to create the maze

43. 43 To play the game, resolve issues, in OO context, with OO principles: How do we handle direction? Who keeps track of player’s location: the game? the player? both? How does enter() work? How does player know when s/he wins?

44. 44 How I resolved the issues: How do we handle direction? Make it a first class object Who keeps track of player’s location: The player. If game wants to know, ask player. How does enter() work? Player is in a room facing a specific direction. If s/he tries to enter a room, s/he may also enter a door, if it’s open How does player know when s/he wins? The game declares the winner!

45. Possible “Direction” implementation

46. Possible Player implementation

47. 47 “enter()” for a door

48. 48 Sample Maze

49. 49 write code like this

50. 50 Want the game to work

51. 51 We want flexibility in maze creation Be able to vary the kinds of mazes Rooms with bombs walls that have been bombed enchanted rooms need a spell to enter the door!

52. 52 A room with a bomb

53. 53 What order to study the patterns Since many patterns use other patterns, it’s difficult to start Many of the creational patterns use other patterns, for example, Template Method We will study 5 creational patterns

54. 54 Creational Patterns Chapter 3 of GOF

55. 55 The Builder Pattern pp 97-106 in GOF

56. 56 Basics Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations aka: ?

57. 57 Motivation Permit the same construction process to create different representations Use this pattern when the algorithm for creating a complex object s/b independent of the parts that make up the object & how they’re assembled

58. 58 Structure of the pattern

59. 59 Motivating Example: An RTF converter

60. 60 Collaborations

61. 61 Consequences of Builder Builder gives director an abstract interface for constructing the product the interface lets the builder hide the internal structure of the product Builder improves modularity Gives finer control over the build process constructs product step-by-step only when product is finished does director retrieve it from builder

62. 62 MazeBuilder defines an interface

63. 63 Implementation why no abstract class for product? typically, products differ greatly => little to gain by a common interface empty methods as default in builder let’s clients only override those it needs

64. 64 createMaze becomes:

65. Subclasses do the implementation

66. 66 Builder modularizes room construction

67. 67 to build a door, lookup the rooms

68. The main program

69. 69 Interesting subclass: counting maze builder StandardMazeBuilder is easy to separate from Maze: can have a variety of maze builders each using different classes for Rooms, etc Can make all kinds of subclasses of MazeBuilder, like RandomMazeBuilder a counting maze builder could count Rooms & Doors instead of making them

71. The main calling routine

72. 72 Known uses Smalltalk-80 The Parser class in the compiler subsystem is a director that takes a ProgramNodeBuilder object as an argument When the parser is done, it asks builder for the parse tree The Service Configurator framework from Adaptive Communications Environment uses a builder to construct components using an LALR(1) parser

73. 73 Related Patterns Abstract Factory is similar to Builder: primary difference is that Builder pattern constructs objects step-by-step. Abstract Factory builds families of products Builder returns product as final step; Abstract Factory, product returned immediately “A Composite is what the Builder often builds”

74. 74 The Abstract Factory Pattern pp 87-95 in GOF

75. 75 Basics Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes aka: kit

76. 76 Applicability use Abstract Factory when a family of related product objects is designed to be used together and you need to force this constraint use AF when you want to provide a class library of products and you want to reveal only the interfaces use when the system is independent of how products are created

77. 77 Motivating Example

78. 78 Participants AbstractFactory -- declares an interface for operations that create abstract product objects ConcreteFactory -- implements the operations AbstractProduct -- declares an interface for a type of product object ConcreteProduct - defines the product object to be created by the corresponding concrete factory client -- uses only interfaces declared by AbstractFactory and AbstractProduct

79. Structure of the Pattern

80. 80 Consequences It makes exchanging product families easy It promotes consistency among products isolates concrete classes and help you control the classes of objects that an application creates Supporting product variations is difficult Factories as singletons: An app typically only needs one ConcreteFactory

81. 81 Our Maze Game Example

82. a version of createMaze

84. 84 Known Uses InterViews uses the “kit” suffix to denote AbstractFactory classes. [Lin92] ET++ uses the Abstract Factory pattern to achieve portability across different window systems [WGM88]

85. 85 The Factory Method Pattern pp 107-116 in GOF, and pp 140-165 in Coplien, advanced C++

86. 86 basics Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses aka: Virtual Constructor

87. 87 Guideline of OO design each class should know how to take care of its own business The power of OO derives from: inheritance virtual functions these two enable a user to communicate with an object exclusively through the interface defined by the base class compiler provides “magic” dispatching

88. 88 OO Design OO language constructs isolate a family of classes from knowing details of the number and nature of derived classes, as well as from the implementation details of these classes There are times when this doesn’t work! Virtual Constructors or Factory Method provides a solution

89. 89 Motivating example Consider class Number with derived classes BigInt and Complex, with most derived class operations as virtual in Number. Users can use a pointer or reference to Number, bind the pointer to any of the member of the hierarchy and interact without knowing what “it” is!

90. 90 Number Hierarchy

91. 91 virtual constructors We may want the instantiation to be accomplished from w/in the hierarchy perhaps when number becomes too large, Number switches to a BigInt perhaps when the user takes the sqrt of a negative number, “it” switches to a Complex

92. 92 When to use Factory Method 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

93. 93 Where to build/switch the “number”?

94. 94 Where to build/switch the “number”?

95. 95 Where to build/switch the “number”?

96. 96 Alternatives: Make a derived class the “envelope”

97. 97 Alternative structure for the Pattern

98. 98 Consequences Factory methods eliminate the need to bind application specific classes into your code. creational code only deals with the Product interface code can work with any user-defined ConcreteProduct classes Can connect parallel class hierarchies

99. 99 Implementation Two varieties Creator is a concrete class & provides default implementation factory method used for flexibility Creator class is abstract & does not provide an implementation for the factory method it declares requires subclasses

100. 100 when to use this pattern when the type of an objects is determined from the context in which the object is constructed example: building a window object of the right type & size as a function of the default screen used by the program creating object from file input

101. 101 Atoms -- lexical tokens

102. A numeric atom (letter)

103. The Factory Atom (envelope)

104. FactoryAtom (envelope)

105. 105 Compare with Builder

106. 106 Parameterizing the Factory Parameterized Factory Methods: a variation on the pattern lets the factory method create multiple kinds of products factory method takes a parameter that identifies the type of Product to create all created objects share the Product interface

107. 107 Parameterized Factory Methods

108. creation of game

109. 109 Can make extensions to the game

110. Factory Methods

111. Factory Methods

112. 112 main() creates a bombed maze

114. 114 Related Patterns Factory Method is frequently used with Template Method Abstract Factory is often implemented with Factory Method or Virtual Constructor

115. An alternative approach

116. Alternative Methods

118. 118 Singleton pp 127-134 GOF

119. 119 Basics Intent: Ensure a class has only one instance and provide a global point of access to it aka: ?

120. 120 when to use want exactly one instance of a class accessible to clients from one point want the instance to be extensible can also allow a countable number of instances improvement over global namespace better than static class: can’t change mind methods never virtual

121. 121 Structure of the Pattern

122. 122 Class Declaration

123. 123 Implementation

124. 124 What if Singleton is subclassed

125. 125 Making a single Factory

126. 126 What if there are subclasses of MazeFactory?

  • Login