cosc 340 software engineering design patterns
play

COSC 340: Software Engineering Design Patterns Michael Jantz - PowerPoint PPT Presentation

COSC 340: Software Engineering Design Patterns Michael Jantz Recommended text: Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides COSC 340: Software Engineering 1 Why


  1. Abstract Factory Pattern: Maze Example MazeFactory Implementation • MazeFactory is a collection of factory methods • MazeFactory acts as both the AbstractFactory and a ConcreteFactory COSC 340: Software Engineering 34

  2. Prototype Pattern • Intent ‒ Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype • Motivation ‒ Useful for when a system needs to be independent of how its objects are created, composed, and represented ‒ Enables you to avoid building a class hierarchy of factories that parallels the class hierarchy of products ‒ Example: graphical application for editing musical scores • Solution ‒ Parameterize object creation methods with prototype instance ‒ Create the appropriate objects by copying the prototype COSC 340: Software Engineering 35

  3. Prototype Pattern: Example Graphical Application for Editing Musical Scores • Approach: use a general framework for creating graphical apps • The framework includes a palette of tools for ‒ Adding new music objects (notes, rests, staves) ‒ Selecting, moving, manipulating music objects • Framework design ‒ Abstract graphic class for graphical components ‒ Abstract tool class for defining tools in the palette ‒ GraphicTool class • Creates graphical objects and adds them to the document • Problem: GraphicTool should be part of the (general) graphical framework, but the graphical objects (notes, staves) are specific to the application COSC 340: Software Engineering 36

  4. Prototype Pattern: Example Graphical Application for Editing Musical Scores • Solution: GraphicTool creates new graphics by cloning a prototype instance of a Graphic subclass • GraphicTool is parameterized by the prototype it should clone and add to the document 37

  5. Prototype Pattern: Structure COSC 340: Software Engineering 38

  6. Prototype Pattern: Participants • Prototype (Graphic) ‒ Declares an interface for cloning itself • ConcretePrototype (Staff, WholeNote, HalfNote) ‒ Implements an operation for cloning itself • Client (GraphicTool) ‒ Creates a new object by asking a prototype to clone itself COSC 340: Software Engineering 39

  7. Prototype Pattern: Maze Example COSC 340: Software Engineering 40

  8. Prototype Pattern: Maze Example 41

  9. Prototype Pattern: Maze Example • Initialize with basic maze components to create a prototypical or default maze COSC 340: Software Engineering 42

  10. Prototype Pattern: Maze Example • Initialize with bomb maze components to create a maze with bombs COSC 340: Software Engineering 43

  11. Prototype Pattern: Maze Example • Original definition for Door • Prototype pattern definition for Door 44

  12. Prototype Pattern: Maze Example • Note: BombedWall::Clone returns a Wall*, but the implementation always returns a BombedWall* • This design ensures code that clone the prototype do not have to know about concrete subclasses COSC 340: Software Engineering 45

  13. Structural Patterns • Compose classes and objects to form larger structures • Two types ‒ Structural class patterns use inheritance to compose interfaces or implementations ‒ Structural object patterns compose objects to realize new functionality • Structural patterns we will cover ‒ Composite ‒ Decorator ‒ Adapter COSC 340: Software Engineering 46

  14. Composite Pattern • Compose objects into tree structures that let you treat individual objects and compositions of objects uniformly • Motivation ‒ Having to distinguish between primitive objects and compositions of primitive objects can make the application more complex ‒ Example: grouping components of a graphical application • Solution ‒ Use recursive composition of objects ‒ Use an abstract class to represent both primitive objects and their containers COSC 340: Software Engineering 47

  15. Composite Pattern: Motivation Grouping Components in a Graphical Application • Graphics applications (e.g. drawing editors) often build diagrams out of simple components ‒ Users group components to form larger components • Simple approach: classes for primitive objects (Line, Text) and classes for container objects ‒ Problem: code must treat these objects differently – even if the user treats them identically ‒ Desire a common interface for using and representing both primitive and container objects COSC 340: Software Engineering 48

  16. Composite Pattern: Motivation Grouping Components in a Graphical Application COSC 340: Software Engineering 49

  17. Composite Pattern: Structure COSC 340: Software Engineering 50

  18. Composite Pattern: Participants • Component (Graphic) ‒ Declares the interface for objects in the composition ‒ Implements default behavior for the interface common to all classes, as appropriate ‒ Declares an interface for accessing and managing its child components ‒ (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate • Leaf (Rectangle, Line, Text, etc.) ‒ Represents leaf objects in the composition (a leaf has no children) ‒ Defines behavior for primitive objects in the composition • Composite (Picture) ‒ Defines behavior for components having children ‒ Stores child components ‒ Implements child-related operations in the Component • Client ‒ Manipulates objects in the composition through the Component interface. COSC 340: Software Engineering 51

  19. Composite Pattern: Example Electronic Equipment • The Equipment class defines an interface for a hierarchy of electronic equipment COSC 340: Software Engineering 52

  20. Composite Pattern: Example Electronic Equipment • FloppyDisk is a Leaf class • It defines the interface for one of the individual components in the hierarchy COSC 340: Software Engineering 53

  21. Composite Pattern: Example Electronic Equipment • CompositeEquipment is a base class for equipment that contains other equipment COSC 340: Software Engineering 54

  22. Composite Pattern: Example Electronic Equipment • Operations for CompositeEquipment are defined in terms of their children COSC 340: Software Engineering 55

  23. Composite Pattern: Example Electronic Equipment • Client code treats Equipment and CompositeEquipment objects in a uniform way COSC 340: Software Engineering 56

  24. Composite Pattern: Consequences Benefits and Drawbacks • Results in class hierarchies consisting of primitive objects and composite objects • Benefits ‒ Makes the client simpler ‒ Makes it easier to add new types of components • Drawbacks ‒ Can make your design overly general COSC 340: Software Engineering 57

  25. Adapter Pattern • Convert (or "adapt") the interface of a class into another interface expected by the client code • Also known as "wrapper" • Motivation ‒ A toolkit might not be usable only because its interface does not match the domain-specific interface expected by the application ‒ Example: drawing editor program with text boxes • Solution ‒ Use multiple inheritance to adapt one interface to another ‒ Use object composition to implement one interface in terms of another COSC 340: Software Engineering 58

  26. Adapter Pattern: Motivation DrawingEditor Program • Program allows users to draw and arrange graphical elements (lines, polygons, text) into pictures and diagrams ‒ Shape class defines graphical objects (has an editable shape and can draw itself) ‒ Each kind of graphical object is a subclass of shape (LineShape, PolygonShape, etc) • TextShape is more difficult to implement ‒ TextView class available from another toolkit, but does not fit the Shape interface ‒ How to use TextView even though our drawing class must conform to a different and incompatible interface? ‒ Solution: create an adapter class that adapts TextView's interface for use with the Drawing Editor program COSC 340: Software Engineering 59

  27. Adapter Pattern: Motivation DrawingEditor Program COSC 340: Software Engineering 60

  28. Adapter Pattern: Structure Using Object Composition COSC 340: Software Engineering 61

  29. Adapter Pattern: Structure Using Multiple Inheritance COSC 340: Software Engineering 62

  30. Adapter Pattern: Participants • Target (Shape) ‒ Defines the domain-specific interface that Client uses • Client (DrawingEditor) ‒ Collaborates with objects conforming to the Target interface • Adaptee (TextView) ‒ Defines an existing interface that needs adapting • Adapter (TextShape) ‒ Adapts the interface of Adaptee to the Target interface COSC 340: Software Engineering 63

  31. Adapter Pattern: Sample Code COSC 340: Software Engineering 64

  32. Adapter Pattern: Sample Code Using Multiple Inheritance COSC 340: Software Engineering 65

  33. Adapter Pattern: Sample Code Using Multiple Inheritance 66

  34. Adapter Pattern: Sample Code Using Object Composition COSC 340: Software Engineering 67

  35. Adapter Pattern: Sample Code Using Object Composition COSC 340: Software Engineering 68

  36. Decorator Pattern • Attach additional responsibilities to an object dynamically • Also known as "wrapper" • Motivation ‒ Often want to add responsibilities to individual objects, not an entire class ‒ Class inheritance can be inflexible • Solution ‒ Enclose the target object in another object that adds the functionality ‒ The enclosing object is called a decorator ‒ The decorator forwards requests to the target and may perform additional actions before or after forwarding COSC 340: Software Engineering 69

  37. Decorator Pattern: Example aTextView with aScrollDecorator and aBorderDecorator COSC 340: Software Engineering 70

  38. Decorator Pattern: Example aTextView with aScrollDecorator and aBorderDecorator COSC 340: Software Engineering 71

  39. Decorator Pattern: Structure COSC 340: Software Engineering 72

  40. Decorator Pattern: Participants • Component (VisualComponent) ‒ Defines the interface for objects that can have responsibilities added to them dynamically • ConcreteComponent (TextView) ‒ Defines an object to which additional responsibilities can be attached • Decorator ‒ Maintains a reference to a Component object and defines an interface that conforms to Component's interface • ConcreteDecorator (BorderDecorator, ScrollDecorator) ‒ Adds responsibilities to the component COSC 340: Software Engineering 73

  41. Decorator Pattern: Sample Code • VisualComponent is the Component abstract base class COSC 340: Software Engineering 74

  42. Decorator Pattern: Sample Code • Decorator subclass is used as a base class for creating new decorations • For operations declared in the VisualComponent interface, Decorator passes the request to the _component object COSC 340: Software Engineering 75

  43. Decorator Pattern: Sample Code • Subclasses of Decorator define specific decorations COSC 340: Software Engineering 76

  44. Decorator Pattern: Sample Code • Placing a TextView into the window with no decoration COSC 340: Software Engineering 77

  45. Decorator Pattern: Sample Code • Adding a TextView with border and scrolling capabilities COSC 340: Software Engineering 78

  46. Decorator Pattern: Consequences Benefits and Liabilities • Benefits ‒ More flexibility than static inheritance • Responsiblities added / removed at run-time • Inheritance requires a new class for each additional responsiblity ‒ Avoids feature-laden classes high up in the hierarchy • Liabilities ‒ A decorator and its component are not identical • Complicates testing for identity ‒ Lots of little objects COSC 340: Software Engineering 79

  47. Singleton Pattern • Intent ‒ Ensure a class only has one instance, and provide a global point of access to it • Motivation ‒ Often important for classes to have exactly one instance (e.g. we only want one file system or window manager) ‒ Global variable does not prevent you from instantiating multiple objects • Solution ‒ Class itself is responsible for keeping track of the sole instance ‒ The class ensures no other instances can be created, and provides access to the sole instance COSC 340: Software Engineering 80

  48. Singleton Pattern Implementation: Ensuring a Unique Instance COSC 340: Software Engineering 81

  49. Singleton Pattern Implementation: Ensuring a Unique Instance • Access the singleton through the Instance function • _instance variable initialized on first access • Why not just define a global or static instance variable (initialize automatically)? • Cannot guarantee only one instance of the Singleton type • Runtime initialization allows you to define when the object is initialized COSC 340: Software Engineering 82

  50. Singleton Pattern Example: MazeFactory COSC 340: Software Engineering 83

  51. Singleton Pattern Example: MazeFactory COSC 340: Software Engineering 84

  52. Singleton Pattern: Uses and Benefits • Use Singleton when ‒ There must be exactly one instance of a class, and it must be accessible from a well-known access point ‒ The sole instance should be extensible by sub-classing, and you want to be able to use an extended instance without modifying other code • Benefits ‒ Controlled access to a single instance ‒ Reduced name space (no global variables in the name space) ‒ Singleton class can be sub-classed – and you can configure the application with an instance of the class you need at run-time ‒ Can flexibly change the number of allowable instances COSC 340: Software Engineering 85

  53. Behavioral Patterns • Concerned with algorithms and the assignment of responsibilities between objects • Two types ‒ Behavioral class patterns ‒ Behavioral object patterns • Behavioral patterns we will look at ‒ Template Method ‒ Observer ‒ Iterator COSC 340: Software Engineering 86

  54. Template Method Pattern • Define the skeleton of an algorithm in an operation, deferring some steps to subclasses • Motivation ‒ Often useful to allow subclasses to redefine parts of an algorithm without changing the algorithm's structure • Solution ‒ Define an algorithm in terms of abstract operations that subclasses override to provide concrete behavior • Example: app framework with Application and Document classes COSC 340: Software Engineering 87

  55. Template Method Pattern: Example Application Framework with Application and Document classes COSC 340: Software Engineering 88

  56. Template Method Pattern: Example Application Framework with Application and Document classes • TM fixes the ordering of the steps, but allows subclasses to vary what happens at each step COSC 340: Software Engineering 89

  57. Template Method Pattern: Structure COSC 340: Software Engineering 90

  58. Template Method Pattern: Participants • AbstractClass (Application) ‒ Defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm ‒ Implements a template method defining the skeleton of an algorithm • ConcreteClass (MyApplication) ‒ Implements the primitive operations to carry out subclass-specific steps of the algorithm COSC 340: Software Engineering 91

  59. Observer Pattern • Define a dependencies between objects so that when one object changes state, all its dependents are updated automatically • Motivation ‒ Often need to maintain consistency between related objects ‒ But want to avoid making the classes tightly coupled • Solution ‒ Define a one-to-many relationship between subject and observers ‒ Observers are notified whenever the subject changes state ‒ In response, each observer queries the subject to synchronize its state with the subject's state COSC 340: Software Engineering 92

  60. Observer Pattern: Example Model and View Components • View components (spreadsheet, bar chart, etc.) are dependent on the Model component and should be notified when the Model changes • Observer pattern • Establishes a subject / observer relationship • Subject sends a message to the observers when the state has changed • Also known as publish-subscribe • Subject publishes notifications • Any number of observers can subscribe COSC 340: Software Engineering 93

  61. Observer Pattern: Structure COSC 340: Software Engineering 94

  62. Observer Pattern: Participants • Subject ‒ Knows its observers. Any number of Observer objects may observe a subject ‒ Provides an interface for attaching and detaching Observer objects • Observer ‒ Defines an updating interface for objects that should be notified of changes in a subject • ConcreteSubject ‒ Stores state of interest to ConcreteObserver objects ‒ Sends a notification to its observers when its state changes • ConcreteObserver ‒ Maintains a reference to a ConcreteSubject object ‒ Stores state that should stay consistent with the subject's ‒ Implements the Observer updating interface to keep its state consistent with the subject's COSC 340: Software Engineering 95

  63. Observer Pattern: Collaborations COSC 340: Software Engineering 96

  64. Observer Pattern: Sample Code • Abstract class for the Observer interface • Supports multiple subjects for each observer COSC 340: Software Engineering 97

  65. Observer Pattern: Sample Code • Abstract class for the Subject interface 98

  66. Observer Pattern: Sample Code • ClockTimer is a concrete subject for maintaining the time of day • Tick is called by an internal timer at regular intervals COSC 340: Software Engineering 99

  67. Observer Pattern: Sample Code • DigitalClock class for displaying the time COSC 340: Software Engineering 100

Recommend


More recommend