1 / 41

CS 4240: Introduction to Design Patterns

Learn about design patterns, their essential elements, and see examples of singleton and composite patterns. Explore how these patterns solve recurring problems in software design.

jeannek
Download Presentation

CS 4240: Introduction to 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. CS 4240: Introduction to Design Patterns Readings: Chap. 5 of Design Patterns Explained Also, Chap. 6 and 7 Also, on-line info on Composite pattern (and others) at http://www.oodesign.com

  2. Readings • Chapter 5 of our textbook • Handouts on various patterns

  3. Background, Definition • From Alexander’s work in architecture • Alexander: “a solution to a problem in context.” • Design pattern: a description of a problem that reoccurs and an outline of an approach to solving that problem • Generally domain, language independent • Also, analysis patterns

  4. Design Patterns: Essential Elements • Pattern name • A vocabulary of patterns is beneficial • Intent • Problem • When to apply the pattern, what context. • How to represent, organize components • Conditions to be met before using • Solution • Design elements: relationships, responsibilities, collaborations • A template for a solution that you implement • Consequences • Results and trade-offs that result from using the pattern • Needed to evaluate design alternatives

  5. Essential Elements (con’td) • Participants and collaborators • Implementation • Generic Structure

  6. Patterns Are (and Aren’t) • Name and description of a proven solution to a problem • Documentation of a design decision • They’re not: • Reusable code, class libraries, etc. (At a higher level) • Do not require complex implementations • Always the best solution to a given situation • Simply “a good thing to do”

  7. Describing Design Patterns • The GoF defined a standard format • Generally followed • Not just a UML diagram! • Pattern Format (13 sections): • Pattern name and classification • Intent: what’s it do? Rationale? • Also known as • Motivation • A scenario that illustrates a sample problem and how this patterns helps solve it. • Applicability • For which situations can this be applied? • Structure • Graphical representation (e.g. UML)

  8. Pattern Format (cont’d) • Participants • Classes and objects, their responsibilities • Collaborations • How participants interact • Consequences • Implementation • Pitfalls, hints, techniques, language issues • Sample code • Code fragments that illustrate the pattern • Known uses • From real systems • Related patterns • Similar patterns, collaborating patterns

  9. Example 1: Singleton Pattern • Global variables are bad! • Why? • We often want to use global variables! • Why?

  10. Example 1: Singleton Pattern • Context: Only one instance of a class is created. Everything in the system that needs this class interacts with that one object. • Controlling access: Make this instance accessible to all clients • Solution: • The class has a static variable called theInstance (etc) • The constructor is made private (or protected) • Clients call a public operation getInstance()that returns the one instance • This may construct the instance the very first time or be given an initializer

  11. Singleton: Java implementation public class MySingleton { private static MySingleton theInstance = new MySingleton(); private MySingleton() { // constructor … } public static MySingleton getInstance() { return theInstance; }}

  12. Static Factory Methods • Singleton patterns uses a static factory method • Factory: something that creates an instance • Advantages over a public constructor • They have names. Example:BigInteger(int, int, random) vs.BigInteger.probablePrime() • Might need more than one constructor with same/similar signatures • Can return objects of a subtype (if needed) • Wrapper class example: Double d1 = Double .valueOf(“3.14”); Double d2 = new Double (“3.14”); • More info: Bloch’s Effective Java

  13. Examples from Java Library • In Swing, you can create a Border and add it to a component Border b = BorderFactory.createBevelBorder(3); • Need the exact same border again? • The above method doesn’t create a new one. Just gives you the same one • Note: works because the bevel is immutable

  14. Example from the Java Library • Java can manipulate its own class definitions • Example: Class classObj = Class.forName(“edu.uva.cs441.MyClass”); • Then we can do things to the Class object • What if we call this again? • Only one Class object per Java-class

  15. Example #2: PlayLists and Songs • We saw this in CS201 (maybe)

  16. Could PlayLists “Nest”? • Could a PlayList contain Songs and other PlayLists? • This is the “Composite Design Pattern” • Make PlayList contain • A list of PlayableItems, not Songs • PlayList.play() calls play() on each item • Polymorphism at work

  17. Class Diagram for This Composite

  18. General Class Diagram • Could be many Leaf classes

  19. Polymorphism in Action • Playlist contains a list of PlayableItems • PlayList.play() calls play() on each item for (int i=0; i<list.size(); ++i) { ( (PlayableItem) list.get(i) ).play(); } • Will call the Song.play() or PlayList.play() depending on what item i really is • Review question: why is the cast needed?

  20. Façade Pattern • Intent: • Simplify interface to set of interfaces in an existing subsystem.Or, need to define new/variant interface • Problem: • Only need part of a complex system.Or, need to interact in a particular way. • Participants, collaborators: • Façade class, subsystem classes, client class

  21. Façade Pattern (cont’d) • Consequences: • Certain subsystem operations may not be available in the façade • Clients may “go around” the facade

  22. Note in textbook • Reduce coupling for client • Existing interfaces requires client to access many objects to carry out task • Façade object may be one object that’s a “gateway” to multiple objects • In other words: the Façade encapsulates the system • Another motto: find what varies and encapsulate it

  23. Examples: • Java’s URL class • Really hides a set of objects and methods • But not easy to see that it does this IMHO • An example from our recent CS1110 textbook • Make I/O easier for beginners • Class StdIn: static methods to read • Class In: create object to read from keyboard, file or URL

  24. Class In from Princeton course text See Javadoc here: http://www.cs.princeton.edu/introcs/stdlib/javadoc/In.html

  25. Encapsulate Scanner, simplify methods public final class In { private Scanner scanner; ... public In() { scanner = new Scanner( new BufferedInputStream(System.in), charsetName); scanner.useLocale(usLocale); }... /** * Is the input stream empty? */ public boolean isEmpty() { return !scanner.hasNext(); }

  26. Create “reader” from filename or URL public In(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner( new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println("Could not open " + s); } }

  27. Think About and Discuss • Façade: any relation to the Law of Demeter? • “Principle of Least Knowledge” • Talk only your immediate friends

  28. Adaptor Pattern • Intent: • Make an existing object match an existing interface that it doesn’t match • Problem: • Existing component has right functionality but doesn’t match the interface used • Interface here? Abstract class (or Java-interface) used polymorphically • Solution: • Wrapper class with delegation etc. • Two flavors: Object Adaptor vs. Class Adaptor

  29. Adaptor Pattern (cont’d) • Participants and Collaborators • Adapter class: “new” interface for… • Adaptee class (existing class) • Target: the needed interface • Client who uses objects of type Target • Consequences: • The good: solves problem and meets intent above! • Some other wrinkles…

  30. Class Diagram for Object Adaptor • Object Adaptor pattern • Note that Adapter is anexample of a “wrapper class” • A common implementation techniqueused in several design patterns

  31. Book’s Example • Abstract class (or interface) Shape • Methods include: display(), fill() • Our code relies on Shape hierarchy and polymorphism • We need a Circle class • Sweet! Another one exists! XXCircle • Bummer! Method names are different • Solution: see book or notes on board

  32. Class Adaptor Pattern • Don’t create a separate object that wraps the existing object • Instead, create new class that • Includes what existing class has (inherit) • Also meets Target interface • With a Java interface, or multiple inheritance in other languages

  33. Class Adaptor example • Problem: • Existing code has a CommandBuffer class • Doesn’t have an Iterator • You have code that could do great things if only you could use CommandBuffer as if it were Iterable

  34. Example of Class Adaptor pattern • The new class implements Iterator methods in terms of getCommand() etc defined in existing class • No pair of objects: just an instance of new class

  35. Think About and Discuss • Class adaptors are different than object adaptors • Does this difference relate to a “rule” or “principle” of OO design we’ve seen?

  36. Comparing Façade and Adaptor • Similarities: • Both designed to help us use existing classes better • Both can use wrapper objects • Similar implementation solves different problems • Adaptor: existing interface we must design to (not for Façade) • New object used polymorphically • Façade: need simpler interface (not a goal for Adaptor) • See table 7-1 on page 110

  37. Summary of Intro to Design Patterns • Understand background, general principles of design patterns • Examples: • Singleton • Composite • Façade • Adaptor • Recognize them, apply them in simple situations

  38. Exercise: Can you Adapt? • Deprecated Java interface Enumerator • hasMoreElements() • nextElement() • Replaced by interface Iterator • hasNext() • next() • remove()

  39. Your task • Create a class: EnumerationIterator • This let us design and write new code that works with Iterators, andalso interact with legacy code that exposes Enumerators for use to use • First question: class or object adaptor?

  40. Questions to Answer • Question: which classes play which roles in the design pattern? Write this down. • Final question: write Java class with constructor and next() and hasNext().

More Related