1 / 62

CSCE 431: (Object Oriented) Design Patterns

CSCE 431: (Object Oriented) Design Patterns. Some material from R. Martin, Bruegge , Dutoit. Outline. Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary. Context. Requirements elicitation

danika
Download Presentation

CSCE 431: (Object Oriented) Design 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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSCE 431:(Object Oriented)Design Patterns Some material from R. Martin, Bruegge, Dutoit

  2. Outline • Context • Some key concepts and notions of OO • Design patterns • A few more design patterns • Idioms • Summary CSCE 431 OO Design Patterns

  3. Context • Requirements elicitation  Functional model (use cases, formal specifications etc.)  Non-functional requirements • Analysis  Analysis Object Model (class diagrams)  Dynamic Model (state charts, sequence diagrams) • System design  Design goals  Subsystem decomposition • Object design  Object design model (class diagrams) • Implementation  Source code • Testing  Deliverable system (we have not discussed yet) CSCE 431 OO Design Patterns

  4. System Design (One Slide Version) • Subsystem decomposition • Abstraction of the machine(s) • Choosing middleware, GUI frameworks, class libraries, database engines • Application domain components • Possibly choosing off-the-shelf application domain components for select domain functionality • Object design to fill in the rest • Adapt reusable components • Identify new solution classes • Specify subsystem interfaces precisely CSCE 431 OO Design Patterns

  5. Object Design • Purpose • Prepare for implementing the system model • Transform the system model for better implementability/extensibility/performance/. . . • Explore ways to implement the system model • The result of object design should match the structure of the implementation CSCE 431 OO Design Patterns

  6. Activities • Reuse: identify and adapt existing solutions • Off-the-shelf components • Libraries • Design patterns • Interface specification • Specs of each class interface • APIs of subsystems • Object model restructuring • To improve some characteristics (extensibility, understandability, etc.) • Object model optimization • Greater speed, lower memory use, etc. CSCE 431 OO Design Patterns

  7. Outline • Context • Some key concepts and notions of OO • Design patterns • A few more design patterns • Idioms • Summary CSCE 431 OO Design Patterns

  8. Outline • Some principles of object-oriented programming • About modularity • OO twists on modularity, inheritance • Substitutability • Delegation • Introduction to design patterns • A few design patterns CSCE 431 OO Design Patterns

  9. Modularity • Parnas,On the Criteria to be Used in Decomposing Systems into Modules, 1972 • Every module should be known to the outside world through an official, “public” interface • The rest of the module’s properties comprises its “secrets” • It should be impossible to access the secrets from the outside • Inheritance, encapsulation, related features in OO languages aimed at supporting information hiding • Aside: Parnas says the following about OO languages • Could be helpful, but not really needed • Language is not the issue, design is what matters • Some features make it easy to do things wrong CSCE 431 OO Design Patterns

  10. Characteristics of Good Modularization • Low coupling and high cohesion • Minimize dependencies • Changes are localized • Maximize unity • Modules work well together CSCE 431 OO Design Patterns

  11. Encapsulation • Booch The process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation • Casual definition: bundling data and methods, with access protection • Encapsulation enables object invariants to be enforced CSCE 431 OO Design Patterns

  12. Inheritance • Where used: • Organization (during analysis) • Inheritance helps in expressing generalization and specialization in taxonomies that deal with the application domain • Primary use: discussion with domain experts and customers • Reuse (during object design) • Inheritance helps in reusing models and code to deal with the solution domain • Goal is to reduce redundancy and obtain extensibility • Primary use: developers CSCE 431 OO Design Patterns

  13. Implementation vs. Interface Inheritance • Implementation inheritance • Also called class inheritance • Goal is to extend an applications’ functionality by reusing functionality from the superclass • Inherit from an existing class with some or all operations already implemented • Specification inheritance • Also called subtyping • Inherit a specification for which to provide an implementation • The specification is an abstract class with all the operations specified but not yet implemented • Meyer gives a taxonomy of 13 different kinds of uses of inheritance CSCE 431 OO Design Patterns

  14. Extensibility: Open Closed Principle (OCP) A module should be open for extension but closed for modification • B. Meyer (OOSC98) • Essentially suggests that defining new subclasses should suffice to evolve code • (maybe in Eiffel, as its type system gives considerable freedom) • Nice if works • Requires guessing/knowing the variation points • Requires obeying Liskov Substitution Principle CSCE 431 OO Design Patterns

  15. Liskov Substitution Principle • Simple formulation Subclasses should be substitutable for their base classes • Somewhat more precise formulation • Note that notion of subtyping is behavioral • Cannot be checked Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T • Liskov, Wing, 1994 • Same in code class Base { . . . }; class Derived : public Base { . . . }; void q(Base& b); // should work, even if b an // instance of Derived CSCE 431 OO Design Patterns

  16. LSP Violation • “Circle is-an ellipse” class circle : public ellipse { ... void set_foci ( Point p1 , Point p2) { a = p1; b = p1 } } void f( Ellipse & e) { Point a( -1 ,0) , b (1 ,0); e.set_foci(a, b); assert (e.get_focus_a() == a); assert (e.get_focus_b() == b); } • set_foci’spostcondition (something like a == p1, b == p2) not true for circles • Fixes at the client calling f easily lead to Open Closed Principle violations CSCE 431 OO Design Patterns

  17. LSP and Design by Contract class A { @invariant i1; @pre p1; virtual void foo (...); @post q1 } class B : public A { @invariant i2; @pre p2; void foo (...); @post q2 } • What are the relations? p1?p2 q1?q2 i1?i2 • A method in a derived class must • Have preconditions that are no stronger than those of the base’s method it is overriding • Have postconditionsno weaker than those of the base’s method it is overriding • “derived methods should expect no more and provide no less” p1  p2 q1  q2 i1  i2 CSCE 431 OO Design Patterns

  18. Inheritance vs. Delegation Consider this inheritance relation: Implementation inheritance vs. delegation class HashTable { void put ( Object key , Object element ); Object get ( Object key ); booleancontainsKey ( Object ); booleancontainsValue ( Object ); ... } class MySet extends HashTable { void put ( Object element ) { if (! containsKey ( element )) { put ( element , this ); } } booleancontainsValue ( Object element ) { return containsKey ( element ); } ... } class MySet { private Hashtable table ; MySet() { table = Hashtable (); } void put ( Object element ) { if (! containsValue ( element )) { table.put( element , this ); } } booleancontainsValue ( Object element ) { return table.containsKey( element ); } ... } CSCE 431 OO Design Patterns

  19. Inheritance vs. Delegation • Inheritance should be used only if real taxonomies exist • If LSP (roughly) holds • Delegation should be preferred when reusing implementations • Next: design patterns • And we will notice that most design patterns are some compositions/combinations of delegation and inheritance CSCE 431 OO Design Patterns

  20. Outline • Context • Some key concepts and notions of OO • Design patterns • A few more design patterns • Idioms • Summary CSCE 431 OO Design Patterns

  21. Design Patterns Motivation • Not every problem solved with a solution developed “from scratch” • Desirable to reuse solutions • Recording and cataloging experience in SW design often not done systematically, or at all • Learning how to design starts by studying other designs CSCE 431 OO Design Patterns

  22. Characterizing Design Patterns • Reusable designs • Capturing design knowledge that • Is too “high-level” to write as an abstraction in a library • What is too high-level depends on the language, of course • Modifiable abstractions/designs • Basic idea: avoid “re-inventing the wheel” • Capture well-tested solutions to oft-occurring situations • Modularize design! CSCE 431 OO Design Patterns

  23. 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. Visually pleasing and practical structures for an application and/or setting could be described by a pattern language. - Christopher Alexander • For example, desirable farmhouses in the Bernese Oberland area of Switzerland used these patterns: North-South Axis Garden to the South West-Facing Entrance Down the Slope Pitched Roof Two Floors Half-Hipped End Hay Loft at the Back Balcony Toward the Garden Bedrooms in Front Carved Ornaments CSCE 431 OO Design Patterns

  24. Patterns in Software • OOPSLA 1987, Kent Beck and Ward Cunningham, Using Pattern Languages for Object-Oriented Programs • Applied Alexander’s pattern language to UI design • Window Per Task • Few Panes Per Window • Standard Panes • Short Menus • Nouns and Verbs • More work followed, culminating to the DesignPatterns book in 1995 CSCE 431 OO Design Patterns

  25. GoF Book CSCE 431 OO Design Patterns

  26. 23 Patterns in GoF Book CSCE 431 OO Design Patterns

  27. Creational Patterns Builder Separates construction from representation (how to build, e.g., Composite objects) Factory method Create objects without hardcoding the class name AbstractFactory Groups factories with a common theme Prototype Cloning from prototypes Singleton Restricts objects to no more than one instance, with a single point of access CSCE 431 OO Design Patterns

  28. Structural Patterns Adapter Creates a new interface for an existing unmodifiable interface Bridge Separates an abstraction form its implementation Composite Tree structure of objects that allows uniform manipulation Decorator Dynamically extensible behavior (instead of statically, as with subclassing) Façade Unified interface to simplify use (wrap APIs, etc.) Flyweight Share similar data among many objects Proxy A class serving as a placeholder, possibly adding functionality, to another class CSCE 431 OO Design Patterns

  29. Behavioral Patterns Chain of Responsibility Delegate command objects to a chain of processing objects Command Wrap a command into an object with all the information that is needed to execute it Interpreter How to interpret ASTs represented as Composite Objects Iterator Access objects sequentially without exposing the underlying representation Mediator Encapsulate, and restrict the form of, communication between objects into a dedicated middleman Memento Undo functionality Observer Publish/subscribe State Object behavior changes when state changes (modes) Strategy Select most suitable algorithm at runtime Template method Algorithm skeleton, with subclasses providing concrete behavior Visitor Separate algorithm from structure of the object it operates on (double dispatching) CSCE 431 OO Design Patterns

  30. Structure of a Design Pattern • Four elements • A unique name • A problem description • Situations in which the pattern applies • Problems addressed • A solution • Stated as a set of collaborating classes and interfaces • Often uses class diagrams, sequence diagrams, state charts, etc. • A set of consequences that describes the trade-offs and alternatives w.r.t. the design goals the pattern addresses CSCE 431 OO Design Patterns

  31. GoF Book’s Pattern Structure • Pattern Name and Classification • Intent • “Why use this pattern?” • Also known as • Motivation (Forces) • Often an example scenario • Applicability • Structure • Often class and interaction diagrams • Participants • Classes and objects involved, and their roles • Collaborations • How classes/objects interact • Consequences • Implementation • Sample Code • Concrete example of how to use the pattern (in code) • Known Uses • Related Patterns CSCE 431 OO Design Patterns

  32. Composite Pattern: Motivation There are times when a program needs to manipulate a tree data structure and it is necessary to treat both Branches as well as Leaf Nodes uniformly. Consider for example a program that manipulates a file system. A file system is a tree structure that contains Branches which are Folders as well as Leaf nodes which are Files. Note that a folder object usually contains one or more file or folder objects and thus is a complex object where a file is a simple object. Note also that since files and folders have many operations and attributes in common, such as moving and copying a file or a folder, listing file or folder attributes such as file name and size, it would be easier and more convenient to treat both file and folder objects uniformly by defining a File System Resource Interface. CSCE 431 OO Design Patterns

  33. Composite Pattern: Intent • The intent of this pattern is to compose objects into tree structures to represent part-whole hierarchies • Composite lets clients treat individual objects and compositions of objects uniformly CSCE 431 OO Design Patterns

  34. Composite Pattern: Implementation & Participants Component Component is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition. For example a file system resource defines move, copy, rename, and getSize methods for files and folders. Leaf Leafs are objects that have no children. They implement services described by the Component interface. For example a file object implements move, copy, rename, as well as getSizemethods which are related to the Component interface. Composite A Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components. In addition composites provide additional methods for adding, removing, as well as getting components. Client The client manipulates objects in the hierarchy using the component interface. A client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a branch or a leaf. The client simply obtains reference to the required node using the component interface, and deals with the node using this interface; it doesn’t matter if the node is a composite or a leaf. CSCE 431 OO Design Patterns

  35. Composite Pattern: Applicability • The composite pattern applies when there is a part-whole hierarchy of objects and a client needs to deal with objects uniformly regardless of the fact that an object might be a leaf or a branch CSCE 431 OO Design Patterns

  36. Example – Graphics Drawing Editor • In graphics editors a graphic can be basic or complex. Examples of simple graphics are lines and circles, where a complex graphic is a picture containing many simple (or complex) graphics. Since simple and complex shapes have operations in common, such as rendering the graphic to a screen, and since graphics follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all graphics uniformly. CSCE 431 OO Design Patterns

  37. Example – Graphics Drawing Editor In the example we can see the following actors: Graphic (Component) Graphic is the abstraction for Line, Circle,etc. objects, (leafs) and Pictureobjects (composites). Line, Circle (Leafs) Objects that have no children. They implement services described by the Graphicinterface. Picture (Composite) A Composite stores child Graphic objects in addition to implementing methods defined by the Graphic interface. Client The Client (such as a graphical editor) manipulates Graphics in the hierarchy. CSCE 431 OO Design Patterns

  38. Composite Pattern: Alternative Implementation Some methods only make sense for Composite objects, such as Add, Remove, and getChild, and in the class diagram above are thus only defined for Composite objects. Prior to calling these methods, one has to cast a Component to a Composite. Alternatively, these methods could be defined in Component, with default implementations that would do nothing. CSCE 431 OO Design Patterns

  39. Composite Pattern: Consequences • The composite pattern defines class hierarchies consisting of primitive objects and composite objects. Primitive objects can be composed into more complex objects, which in turn can be composed. • Clients treat primitive and composite objects uniformly through a component interface which makes client code simple. • Adding new components can be easy and client code does not need to be changed since client deals with the new components through the component interface. CSCE 431 OO Design Patterns

  40. Composite Pattern: Related Patterns • Decorator Pattern • Decorator is often used with Composite. When decorators and composites are used together, they will usually have a common parent class. So decorators will have to support the Componentinterface with operations like Add, Remove, and GetChild. CSCE 431 OO Design Patterns

  41. Composite Pattern: Known Uses • File system implementation as discussed previously • Graphics editors as discussed previously CSCE 431 OO Design Patterns

  42. Observations • Design patterns make use of interfaces, information hiding, polymorphism, indirection • A pattern typically consists of several classes that may have complex associations • Design patterns can thus make a design more complex, and decrease performance • The tradeoff between added complexity and the potential pay-offs (modularity, extensibility, portability, etc.) needs to be considered CSCE 431 OO Design Patterns

  43. Outline • Context • Some key concepts and notions of OO • Design patterns • A few more design patterns • Idioms • Summary CSCE 431 OO Design Patterns

  44. Factory Method • 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. • Defining a virtual constructor. • The new operator considered harmful. CSCE 431 OO Design Patterns

  45. Example Problem • A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation. CSCE 431 OO Design Patterns

  46. Visitor Pattern • Intent • Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. • The classic technique for recovering lost type information. • Do the right thing based on the type of two objects. • Double dispatch • Problem Many distinct and unrelated operations need to be performed on node objects in a heterogeneous aggregate structure. You want to avoid “polluting” the node classes with these operations. And, you do not want to have to query the type of each node and cast the pointer to the correct type before performing the desired operation. CSCE 431 OO Design Patterns

  47. Visitor Pattern • A “static” class hierarchy, possibly tree-like, expressed using the Composite Pattern • Each class in this hierarchy defines an accept(visitor&) method • acceptmethods send this pointer to the visitor • visitor abstract base class • containing visit(a) overload for each class a in the static hierarchy • Each derived class of visitor implements some of the visit() overloads • Traversal pattern can be either fixed in the accept methods, or left to be expressed in the visit methods CSCE 431 OO Design Patterns

  48. Visitor Pattern: Class Diagram CSCE 431 OO Design Patterns

  49. Visitor Pattern: Sequence Diagram CSCE 431 OO Design Patterns

  50. Outline • Context • Some key concepts and notions of OO • Design patterns • A few more design patterns • Idioms • Summary CSCE 431 OO Design Patterns

More Related