Design Patterns” *
Total Page:16
File Type:pdf, Size:1020Kb
Example of a Pattern Software ! Composite Pattern ! Previous UML: Item “Design Patterns” * Atom Container What started it And then came ... •(aka “Gang of four”) Two books on architecture, by Christopher Alexander, et al. Does not use UML, uses earlier Booch Notation CS 121 Patterns Links (http://www.cs.hmc.edu/courses/2001/spring/cs121/patterns.html) Definition of a Pattern ! Patterns Home Page ! Introduction to Patterns (emphasis on Alexander) ! Carleton Pattern Repository ! Design Patterns, Pattern Languages, and Frameworks (Douglas Schmidt) ! a solution to a recurrent problem ! Essential Software Design Patterns (Walter F. Tichy) ! Patterns in Ja va AWT ! Design Patterns in Dynamic Programming (Peter Norvig) ! The Tao of Design (John Schettino) ! not a “concrete” solution, but an ! Source Code for GoF book ! GoF Pattern Template ! IAP '97 abstract version of it ! Pattern Depot ! Design Patterns, an unbiased assessment (Bryan Dudash) ! Patterns and Software: Essential Concepts and Terminology (with links) (Brad Appleton) ! four essential elements: ! Big Ball of Mud ! Scott Ambler's Writings ! A Pattern Language for Pattern Writing (Gerard Meszaros, Jim Doble) ! Name of the Pattern ! Synopses (Mark Grand) ! UML@Work - From Analysis to Implementation (Hitz, Kappel, Retschitzegger) ! Human-Com puter Interface (HCI) Patterns (Jenifer Tidwell) ! Roundabout, a Pattern Language for Recursive Programming (Eugene Wallingford) ! The Problem ! Loop Patterns (Owen Astrachan, Eugene Wallingford) ! Object Recursion (Bobby Woolf) ! A Development Process Generative Pattern Language (James O. Coplien) ! The Solution ! Papers on patterns and HCI (Human-Computer Interfaces) ! Pedagogical Patterns ! AntiPatterns tutorial ! Consequences, tradeoffs ! Antipatterns of Scholarship ! Cetus Links Uses of Patterns Patterns are not ... ! Conversational “handle” on which to ! Classes hang ideas and concepts ! Libraries ! To direct the user to a known solution ! Reusable packages for a kind of problem ! Higher-order functions (?!) ! To help focus a design ! As a vehicle for refining solution techniques Examples of Patterns Example: Composite Pattern ! “Design Patterns” book lists 23 patterns, ! Name: Composite in several categories. ! The Problem: Construct a class of ! These are sometimes annotated GoF objects wherein (“Gang of Four”). ! objects can either be indivisible or have multiple components. ! Many others have contributed additional ! a collection of components can be treated patterns. as a single object by a client. ! The Solution: The one we have shown ! Consequences, tradeoffs Non-Recursive Examples of Composite Patterns Composite Pattern UML Whole ! Drawing program shape: rectangle, oval, group: set of shapes ! File systems, files, directories, links ! S expressions PartType1 PartType2 PartType3 SubPartType1 SubPartType2 Tradeoffs in Patterns to be Discussed Composite Pattern (alphabetized) ! Whether recursive structure is needed, or will “flat” ! Adapter ! Memento structure suffice ! Cache ! Model-View-Controller ! Whether ordering of components is significant ! Composite ! Observer ! Whether components refer back to parents ! Decorator ! Proxy ! Whether components can be shared ! Delegation ! Singleton ! Who should delete the children ! Façade ! State ! Whether children are represented as a list or simply ! Interface ! Stream enumerated ! Iterator ! Visitor ! Data structure issues (whether to use struct, array,linked list, etc.) Iterator Pattern Iterator Pattern UML ! (GoF, p 257) aka Cursor Pattern Iterator * Container first() ! provides a way to enumerate the elements in next() Interfaces a Composite without exposing the internal current() createIterator() structure of the implementation. done() ! There can be multiple Iterators on a given container. anIterator * aContainer ! Example: In Java, the Enumeration and first() Implementation next() Iterator interfaces do this. In STL, there are current() createIterator() templates for many iterator classes. done() Iterator Pattern in C++ STL Iterator Pattern in Java ! General ! C++: ! Informal ! Java: Methods: Container<Type>::Iterator myIterator; Methods: Enumeration e = container.elements(); ! first() ! myIterator = container.begin(); ! first() ! (implied in initialization) ! next() ! myIterator++; ! next() ! nextElement() ! done() ! myIterator == container.end(); ! ! done() ! hasMoreElements() ! current() ! *myIterator ! currentItem() ! (none- save result of nextElement()) ! Syntax is that of a pointer Exercise Visitor Pattern ! (GoF, p 331) ! Consider a composite that structures its elements as directed, ordered, tree. ! Similar to the Iterator pattern, except that rather than passing objects outside during the enumeration, a Visitor object ! What kinds of iterators are possible? is passed into the Container. ! ! What are the methods on each iterator? The Visitor works on the objects while inside the Container. ! Can add new operations without changing structure of elements. Visitor Pattern UML Visitor in C++ ! class Container<Type> { Visitor * Container next() Interface acceptVisitor(Visitor<Type>); visit() …. acceptVisitor() done() } ! class Visitor<Type> { aVisitor<T> * aContainer<T> visit(<Type> Thing); // Do something to Thing next(); // Advance to the next. next() Implementation boolean done(); // Tell if no more things. visit(T) acceptVisitor() done() } Exercise Façade Pattern ! (GoF, p 185) ! What are the relative Advantages of ! An entire sub-system or set of classes, etc. is Visitor vs. Iterator? given a single simple interface ! Problems solved: ! shield the user against the internal complexity of how the classes are used together ! bundle less-coupled components Façade Pattern Example Façade Pattern VisualTool ! In building using a façade pattern, it is important that the individual components not drawShape() addText() depend on the façade itself. ! This would introduce cross-coupling, which is undesirable. ! Preferably they don’t depend on each other ShapeDrawer TextEditor either. ! When the façade is “removed”, the components should “fall apart” as their original, uncoupled or loosely-coupled, entities. Rather than Make the Façade a Single Class, A Package could be used as a Façade ! A package is a group of related classes. Brief Digression on ! Packages can have sub-packages. Packages ! Visibility can be controlled. UML Package Notation designates inter-package dependency Packages/Dependency notation in UML Coupling / Cohesion Terminology Dependency Company ! Two packages (or classes, for that Sales Accounting matter) between which there is a high- degree of interplay are said to be strongly-coupled. Marketing Shipping ! Strong coupling is considered undesirable; loosely-coupled is better for packages and classes. Coupling / Cohesion Terminology Coupling / Cohesion Summary ! A set of methods for a class, or classes ! Coupling is bad. in a package, are said to be cohesive (or “coherent”) if they provide aspects of ! Cohesion (coherence) is good. a uniform model for dealing with the objects / classes. ! Cohesiveness is desirable; it is a mark of a careful design. A Portion of a About Packages Java Package Hierarchy ! Innermost packages contain classes jav a.ne t jav a. rmi ! Cyclic dependencies among packages jav a. rmi .a ctiv atio n should be avoided: break them, or combine jav a. rmi .dgc into a single package. jav a. rmi .r egis try ! Packages can help delineate work- jav a. rmi .s erve r breakdown among teams, and can thus serve jav a.se cur ity as a management device jav a.se cur ity. acl jav a.se cur ity. cert ! Consider Java package construct. jav a.se cur ity. inte rfa ces ! Equivalent in C++ is namespaces jav a.se cur ity. spec Namespaces in C++ C++ Namespace Example ! Without Namespaces, there is, in effect, one big flat name space. ! The danger is conflicting names in DB two parallel RT namespaces different modules and name space “pollution” by modules with lots of names. sub- OODB RDB namespaces ! Namespace construct allows structuring object-oriented relational into an arbitrary number of hierarchical databases databases levels. realtime databases C++ Namespace Example nam espa ce D B nam espa ce R T qualified names { { c lass A n ames pace OODB { { cla ss A }; RT: :A DB: :OOD B::A } { } ; Returning to Patterns } non-conflicting n ames pace RDB DB: :RDB ::A { cla ss A { }; } } Decorator Pattern Decorator Class Structure ! (GoF, p 175) ! At least three possibilities: ! aka Wrapper (one version thereof) ! The decorating class inherits from the decorated class (“direct” decoration). ! Enclose an object of one class in another class that “decorates” the ! The decorating class aggregates or composes a member of the decorated original objects (e.g. scrollbars or a class (“decoration by delegation”). border around a window). ! A third class aggregates or composes ! Examples: streams of various types both the decorated class and the (OutputStream, FileOutputStream, decoration. PrintStream, …) Adapter Pattern Adapter Pattern based on Association ! (GoF, p 139) Pre-Existing ! aka Binding, Wrapper (another version) Target Adaptee Client ! Adapts one or more existing APIs to fit Request() ExistingRequest() another API specification (one that adaptee Association clients expect). Interface inheritance Adapter ! (API = Application Programming Request() Interface) Adapter Pattern Adapter Example based on Association ! An interface defines a Stack. ! A dynamic array implementation defines Stack Array Client an Array. push() addItem() ! An adapter defines an ArrayStack,