Design PatternsSlide 2GoalsObservationsObservations (cont.)Documentation FormatTypes of Design PatternsCreational PatternsStructural PatternsBehavioral PatternsBehavioral Patterns (cont.)Iterator PatternSlide 13Iterator ExampleSingleton PatternSingleton ExampleAdapter PatternSlide 18Adapter ExampleSlide 20Factory PatternSlide 22Factory ExampleDecorator PatternSlide 25Decorator ExampleSlide 27Slide 28Design PatternsFawzi EmadChau-Wen TsengDepartment of Computer ScienceUniversity of Maryland, College ParkDesign PatternsDescriptions of reusable solutions to common software design problemsCaptures the experience of expertsRationale for designTradeoffs Codifies design in reusable formExampleIterator patternGoalsSolve common programming challengesImprove reliability of solutionAid rapid software developmentUseful for real-world applicationsObservationsDesign patterns are like recipes – generic solutions to expected situationsDesign patterns are language independentRecognizing when and where to use design patterns requires familiarity & experienceDesign pattern libraries serve as a glossary of idioms for understanding common, but complex solutionsObservations (cont.)Many design patterns may need to fit togetherDesign Patterns (by Gamma et al., a.k.a. Gang of Four, or GOF) list 23 design patternsAround 250 common OO design patternsDesign patterns are used throughout the Java Class LibrariesDocumentation Format1. Motivation or context for pattern2. Prerequisites for using a pattern3. Description of program structure 4. List of participants (classes & objects)5. Collaborations (interactions) between participants6. Consequences of using pattern (good & bad)7. Implementation techniques & issues8. Example codes9. Known uses 10. Related patternsTypes of Design PatternsCreationalDeal with the best way to create objects StructuralWays to bring together groups of objectsBehavioral Ways for objects to communicate & interactCreational Patterns1. Abstract Factory- Creates an instance of several families of classes2. Builder - Separates object construction from its representation3. Factory Method - Creates an instance of several derived classes4. Prototype - A fully initialized instance to be copied or cloned5. Singleton - A class of which only a single instance can existStructural Patterns6. Adapter - Match interfaces of different classes7. Bridge - Separates an object’s interface from its implementation8. Composite - A tree structure of simple and composite objects9. Decorator - Add responsibilities to objects dynamically10. Façade - Single class that represents an entire subsystem11. Flyweight - Fine-grained instance used for efficient sharing12. Proxy - Object representing another objectBehavioral Patterns13. Chain of Responsibility - A way of passing a request between a chain of objects14. Command - Encapsulate a command request as an object15. Interpreter - A way to include language elements in a program16. Iterator - Sequentially access the elements of a collection17. Mediator - Defines simplified communication between classes18. Memento - Capture and restore an object's internal stateBehavioral Patterns (cont.)19. Observer - A way of notifying change to a number of classes20. State - Alter an object's behavior when its state changes21. Strategy - Encapsulates an algorithm inside a class22. Template Method - Defer the exact steps of an algorithm to a subclass23. Visitor - Defines a new operation to a class without changing classIterator PatternDefinitionMove through list of objects without knowing its internal representationWhere to use & benefitsUse a standard interface to represent data objectsUses standard iterator built in each standard collection, like List, Sort, or MapNeed to distinguish variations in the traversal of an aggregateIterator PatternExampleIterator for collectionOriginalExamine elements of collection directlyUsing patternCollection provides Iterator class for examining elements in collectionIterator Examplepublic interface Iterator { Bool hasNext(); Object next();} Iterator it = myCollection.iterator();while ( it.hasNext() ) { MyObj x = (MyObj) it.next(); // finds all objects … // in collection}Singleton PatternDefinitionOne instance of a class or value accessible globallyWhere to use & benefitsEnsure unique instance by defining class finalAccess to the instance only via methods providedSingleton Examplepublic class Employee { public static final int ID = 1234; // ID is a singleton} public final class MySingleton {// declare the unique instance of the classprivate static MySingleton uniq = new MySingleton();// private constructor only accessed from this classprivate MySingleton() { … }// return reference to unique instance of classpublic static MySingleton getInstance() { return uniq;}}Adapter PatternDefinitionConvert existing interfaces to new interfaceWhere to use & benefitsHelp match an interfaceMake unrelated classes work togetherIncrease transparency of classesAdapter PatternExampleAdapter from integer Set to integer Priority QueueOriginalInteger set does not support Priority Queue Using patternAdapter provides interface for using Set as Priority QueueAdd needed functionality in Adapter methodsAdapter Examplepublic interface PriorityQueue { // Priority Queue void add(Object o); int size(); Object removeSmallest();}Adapter Examplepublic class PriorityQueueAdapter implements PriorityQueue { Set s; PriorityQueueAdapter(Set s) { this.s = s; } public void add(Object o) { s.add(o); } int size() { return s.size(); } public Integer removeSmallest() { Integer smallest = Integer.MAX_VALUE; Iterator it = s.iterator(); while ( it.hasNext() ) { Integer i = it.next(); if (i.compareTo(smallest) < 0) smallest = i; } s.remove(smallest); return smallest; }}Factory PatternDefinitionProvides an abstraction for deciding which class should be instantiated based on parameters givenWhere to use & benefitsA class cannot anticipate which subclasses must be createdSeparate a family of objects using shared interfaceHide concrete classes from the clientFactory PatternExampleCar Factory produces different Car objectsOriginalDifferent classes implement Car interfaceDirectly instantiate car objectsNeed to modify client to change carsUsing patternUse carFactory class to produce car objectsCan change cars by changing carFactoryFactory Exampleclass 350Z implements Car; // fast
View Full Document