Using Design Patterns to Elaborate upon Design Models Moving from Analysis to Design Examine Design models and initial code to: Improve cohesion Reduce.

Slides:



Advertisements
Similar presentations
Design Patterns.
Advertisements

Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
March Ron McFadyen1 Composite Used to compose objects into tree structures to represent part-whole hierarchies Composite lets clients treat.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
Design Pattern Course Builder Pattern 1 Mahdieh Monzavi AmirKabir University of Technology, Department of Computer Engineering & Information Technology.
Software Design and Documentation Individual Presentation: Composite Pattern 9/11/03.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
7/16/2015Singleton creational design pattern1 Eivind J. Nordby Karlstad University Dept. of Computer Science.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VI Composite, Iterator, and Visitor Patterns.
© SERG Software Design (OOD Patterns) Object-Oriented Design Patterns Topics in Object-Oriented Design Patterns Compliments of Spiros Mancoridis Material.
1 Dept. of Computer Science & Engineering, York University, Toronto Software Development CSE3311 Composite Pattern.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Composite Design Pattern. Motivation – Dynamic Structure.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Composit Pattern.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Design Patterns.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
SE2811 Week 7, Class 1 Composite Pattern Applications Conceptual form Class structure Coding Example Lab Thursday: Quiz SE-2811 Slide design: Dr. Mark.
BTS530: Major Project Planning and Design The Composite Pattern All References and Material From: Design Patterns,by (GOF!) E.Gamma, R.Helm, R.Johnson,
Design Pattern. The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all.
Software Components Creational Patterns.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Design Patterns – II Lecture IV. Singleton Pattern Intent – Ensure a class only has one instance, and provide a global point of access to it Motivation.
SDP Structural Pattern. SDP-2 Structural Patterns Concerned with how classes and objects are composed to form large structures Class Patterns use.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Structural Design Patterns
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IV Structural Patterns.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
CDP-1 9. Creational Pattern. CDP-2 Creational Patterns Abstracts instantiation process Makes system independent of how its objects are –created –composed.
Design Patterns Yonglei Tao. Design Patterns  A design pattern describes a recurring design problem, a solution, and the context in which that solution.
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
Structural Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
Programmeerimine Delphi keskkonnas MTAT Programmeerimine Delphi keskkonnas MTAT Jelena Zaitseva
OO Methodology Elaboration Iteration 2 - Design Patterns -
Class & Object Adapter Patterns (with a focus on Class Adapter) Tim Gutowski CSPP 51023, Winter 2008.
CS212: Object Oriented Analysis and Design Lecture 38: Design Pattern-II.
Design Patterns Introduction
Creational Pattern: Builder When a complex object needs to be created, it is sometimes beneficial to separate the construction of the object from its.
The Visitor Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
1 Advanced Object-oriented Design – Principles and Patterns Structural Design Patterns.
Advanced Object-oriented Design Patterns Creational Design Patterns.
Singleton Pattern Presented By:- Navaneet Kumar ise
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Reference – Object Oriented Software Development Using Java - Jia COP 3331 Object Oriented Analysis and Design Chapter 10 – Patterns Jean Muhammad.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
S.Ducasse Stéphane Ducasse 1 Adapter.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
Design Pattern : Builder SPARCS 04 고윤정. Main Concepts One of Creational Patterns. Process to construct Complex object in Abstract type. –Use the same.
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
Composite Pattern Himanshu Gupta Shashank Hegde CSE776 – Design Patterns Fall 2011 Good composition is like a suspension bridge - each line adds strength.
Design Patterns: Brief Examples
Composite Design Pattern
More Design Patterns 1.
Design Patterns - A few examples
More Design Patterns 1.
Design Patterns A Case Study: Designing a Document Editor
Jim Fawcett CSE776 – Design Patterns Summer 2003
Adapter Pattern 1.
Informatics 122 Software Design II
Behavioral Patterns Part-I introduction UNIT-VI
Ms Munawar Khatoon IV Year I Sem Computer Science Engineering
Structural Patterns: Adapter and Bridge
Introduction to Design Patterns
Design pattern Lecture 6.
Creational Patterns.
Informatics 122 Software Design II
Presentation transcript:

Using Design Patterns to Elaborate upon Design Models Moving from Analysis to Design Examine Design models and initial code to: Improve cohesion Reduce coupling Enhance Reusability GoF Design Patterns should be used to rewrite code to promote these goals

Concordance Example A Concordance consists of an alphabetized list of words appearing in a short document together with an ordered list of the distinct line numbers of lines in which each word appears. Design and implement a short document concordance program. Your program should be able to accept any document, generate a Concordance for the document, and display (or print) the document with its concordance. The domain model will contain the following classes: Concordance Document Word WordList Line LineNumberList

Concordance Domain Model ConcordanceDocumentLineNumberListWordLine Number WordList makes/displays forms * contains * parses *

Implementation Consider class WordList. It has the following requirements: Quick Access -- HashTable O(1), BinarySearchTree O(lg(n)), Vector O(n) Alphabetically ordered display – BinarySearchTree O(ln), Vector O(n), HashTable Choose a BinarySearchTree as the most appropriate data structure Next, consider class LineNumberList. Line numbers are entered in the order they appear, and are read from front to back. Consider using either a Vector or a Queue to list line numbers. Choose the Vector for simplicity and because it can be read non-destructively.

Class Diagram – First Iteration ConcordanceDocument BinSTreeNode WordVectorBinSTree root Line number 0..2 children parent holds

Consequences of Implementation 1 Class Interfaces class Word { private String word; private Vector theLines; public Word (String s, int lineNum) {….} public void addLine(int num) { theLines.add(new Integer(num)); public boolean equals(Word w) { … } public String toString( ) { … } public String getWord( ) { … } public String getLineNums( ) { … } } The statements highlighted in blue indicate attributes and operations flagged by a “House Unwordy Activities Committee” as not properly belonging to class Word. In the interest of high cohesion we will redesign the class

Word Vector Association key BinSTreeNode 0..2 children parent BinSTree root TreeIterator root holds Modified Class Diagram

Additional Design Modification Who is responsible for creating Associations? Concordance? Better Solution – use a Builder to construct Association objects DirectorProductBuilder buildPart( ) getPart( ) ConcreteBuilder buildPart( ) getPart( ) (Concordance) (AssocBuilder) (Association) Builder Pattern

Implementation of Builder Pattern public class Concordance { private Builder assBuilder = new AssocBuilder( ); private Builder docBuilder = new DocumentBuilder( ); private BinsSTree bst = new BinsSTree( ); public void readLines(Document doc) { String delims = " \t\n.,!?;:"; for (int line = 1; true; line++) { try { String text = doc.readLine( ); if (text == null) return; text = text.toLowerCase( ); Enumeration e = new StringTokenizer(text, delims); while (e.hasMoreElements( )) enterWord((String)e.nextElement( ),line); }catch(IOException e) {System.err.println(e.toString( ));} } private void enterWord(String word, int line) { assBuilder.buildPart(word); Association ass = assBuilder.getPart( ); if (!bst.contains(ass) ) { ass.addLine(Integer(line)); bst.add(ass); } else { boolean flag = false: Iterator itr = bst.iterator( ); while (itr.hasNext( ) && !flag) { Association visit = (Association) itr.next( ); if (visit.equals(ass)) { flag = true; visit.addLine(Integer(line)); }

Implementation of Builder Pattern class AssocBuilder implements Builder{ private Association theProduct; public void buildPart ( ) { theProduct = new Association( ); } public void buildPart (String word) { Word w = new Word(word); theProduct = new Association( ) theProduct.addWord(w); } public Association getPart( ) { return theProduct; } class Association implements Comparable{ private Word word; private Vector v; private String key; public Association ( ) { word = null; v = new Vector( ); key = null; } public addWord(Word w) { word = w; key = w.getWord( ); } public addLine(Integer lineNum) { v.add(lineNum); } //methods equals, compareTo, toString, etc. }

Builder Pattern Participants Builder –an Abstract Interface for creating parts of a Product object. ConcreteBuilder – Implements the Builder Interface Defines and keeps track of the representation it creates provides an interface for retrieving the product Director (Concordance) Constructs a Product object using the Builder Interface Product (Association) includes classes that define the constituent parts, including interfaces for assembling the parts into the final result. Intent – Separate the construction of a complex object from its representation, so that the same construction process can create different representations (in our example – Association and Document)

Builder Pattern Collaborations The client creates the Director object and configures it with the desired Builder object. The Director notifies the ConcreteBuilder whenever a part of the Product should be built. The Builder handles requests from the Director and adds parts to the Product The client retrieves the Product from the Builder

Alternative Design Follow the pattern more closely and create a separate Director that directs the construction of the BinSTree and the Document Concordance new TreeBuilder new Director(aTreeBuilder) aDirector constructConcordance (Document ) buildPart( ) create( ) anAssoc new Association getPart() aBinSTree add(anAssoc) aTreeBuilder getResult( ) loop

Alternative Design Classes public class Concordance { private Builder treeBuilder = new TreeBuilder( ); private Builder docBuilder = new DocumentBuilder( ); private DocParser director = new DocParser(treeBuilder); private Document theText; public Concordance( ) { director = new DocParser(treeBuilder); } public void makeConcordance( String filename) { docBuilder.buildPart( filename); theText = docBuilder.getPart( ); director.constructConcordance(theText); bst = treeBuilder.getResult( ) } public void printConcordance( ) {…} }

class DocParser { private BinsSTree bst = new BinSTree( ); private Association ass; private Document theText; private TreeBuilder treeBuilder; public constructConcordance(Document doc) { theText = doc; readLines(theText); } public void readLines(Document doc) { String delims = " \t\n.,!?;:"; for (int line = 1; true; line++) { try { String text = doc.readLine( ); if (text == null) return; text = text.toLowerCase( ); Enumeration e = new StringTokenizer(text, delims); while (e.hasMoreElements( )) enterWord((String)e.nextElement( ),line); }catch(IOException e) {System.err.println(e.toString( ));} } private void enterWord(String word, int line) { Word w = new Word(word); treeBuilder.buildPart(w, line); } Alternative Design Classes

Alternative Design class TreeBuilder { private BinSTree bst = new BinSTree( ); private Association ass; public void buildPart(Word w, int line) { ass = new Association(w, new Integer(line) ); if (!bst.contains(ass) ) { bst.add(ass); } else { boolean flag = false: Iterator itr = bst.iterator( ); while (itr.hasNext( ) && !flag) { Association visit = (Association) itr.next( ); if (visit.equals(ass)) { flag = true; visit.addLine(Integer(line)); } public BinSTree getResult ( ) { return bst; }

Additional Patterns Singleton Adapter Composite

Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it. Applicability Use Singleton pattern when There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. When the sole instance should be extensible by sub-classing, and clients should be able to use an extended instance without modifying their code. Consequences 1.Controlled access to sole instance. Singleton class encapsulates its sole instance and has strict control over how and when clients access it. 2.Reduced name space. It avoids polluting the name space with global variables that store sole instances. 3.Permits refinement of operations and representation. It can be subclassed.

Singleton Pattern – Example code class Singleton { public: static Singleton* Instance( ); protected: Singleton( ); private: static Singleton * _instance; } Singleton class declarationImplementation of Singleton Singleton * Singleton:: _instance = 0; Singleton * Singleton::Instance( ) { if (_instance == 0) _instance = new Singleton( ); return _instance; }

Adapter Pattern Client Target request( ) Adaptee specialRequest( ) Adapter request( ) specialRequest( ) Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. Class Adapter

Adapter Pattern Client Target request( ) Adaptee specialRequest( ) Adapter request( ) adaptee  specialRequest( ) Adapter can add additional functionality to the Adaptee object that the Adaptee object lacks but that Target requires. Object Adapter adaptee

Adapter (a.k.a. Wrapper) Applicability Use the Adapter pattern when You want to use an existing class an its interface does not match the one you need. You want to create a reusable class that cooperates with unrelated or unforseen classes, that is, classes that don’t necessarily have compatible interfaces. (object adapter) you need to use several existing subclasses, but it’s impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class. Participants Target -- defines the domain-specific interface that Client uses. Client -- collaborates with objects conforming to the Target interface. Adaptee -- defines an existing interface that needs adapting. Adapter -- adapts the interface of Adaptee to the Target interface

Composite Pattern Client Composite Operation( ) Add(Component) Remove(Component) GetChild(int) Component Operation( ) Add(Component) Remove(Component) GetChild(int) Leaf Operation( ) For all g in children g.Operation( ); *

Composite Pattern Applicability You want to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly. Participants Component -- 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. Leaf -- defines behavior for primitive objects in the composition. Composite -- defines behavior for components having children. -- stores child components -- implements child-related operations in the Component interface.

Composite Pattern Collaborations Clients use the Component class interface to interact with object in the composite structure. If the recipient is a Leaf, then the request is handled directly. If the recipient is a Composite, then it usually forwards request to its child components, possibly performing additional operations before and/or after forwarding. Consequences Defines class hierarchies consisting of primitive objects and composite objects. Wherever client code expects a primitive object, it can also take a composite object. Makes the client simple. Clients can treat composite structures and individual objects uniformly. Makes it easier to add new kinds of components. Newly defined Composite or Leaf subclasses work automatically with existing structures and client code. Can make your design overly general. It makes it harder to restrict the components of a composite.

Example of Composite Pattern Client Equipment Operation( ) Add(Component) Remove(Component) GetChild(int) FloppyDisk Operation( ) * CompositeEquipment Operation( ) Add(Component) Remove(Component) GetChild(int) CDDrive Operation( ) For all g in children g.Operation( );

Sample Code class Equipment { public: virtual ~Equipment( ); const char* name( ) { return _name; } virtual Watt Power( ); virtual Currency NetPrice( ); virtual Currency DiscountPrice( ); virtual void Add(Equipment *); virtual void Remove(Equipment *); virtual Iterator * CreateIterator( ); protected: Equipment (const char * ); private: const char * _name; } class FloppyDisk : public Equipment { public: FloppyDisk(const char*); virtual ~FloppyDisk( ); virtual Watt Power( ); virtual Currency NetPrice( ); virtual Currency DiscountPrice( ); } class Chassis : public CompositeEquipment{ public: Chassis (const char* ); virtual ~Chassis( ); virtual Watt Power( ); virtual Currency NetPrice( ); virtual Currency DiscountPrice( ); }

Sample Code for Composite Example class CompositeEquipment: public Equipment { public: virtual ~CompositeEquipment( ); virtual Watt Power( ); virtual Currency NetPrice( ); virtual Currency DiscountPrice( ); virtual void Add(Equipment *); virtual void Remove(Equipment *); virtual Iterator * CreateIterator( ); protected: CompositeEquipment(const char *); private: List _equipment; } Currency CompositeEquipoment::NetPrice( ) { Iterator * i = CreateIterator( ); Currency total = 0; for (i -> first( ); i -> isDone( ); i -> next( ) ) { total += i -> currentItem( ) -> NetPrice( ); } delete i; return total; } An implementation of NetPrice( )

Sample code for Composite Pattern Example Assume we have additional Equipment classes such as Bus, Cabinet, etc. We can assemple equipment into a (simple) computer (CompositeEquipment object). Cabinet * cabinet = new Cabinet(“PC Cabinet”); Chassis * chassis = new Chassis(PC Chassis”); Cabinet -> Add(chassis); Bus * bus = new Bus(“MCA Bus”); bus -> Add(new Card(“100 Mbs Ethernet”) ); chassis ->Add(bus); chassis -> Add (new FloppyDisk(“3.5 in Floppy”) ); cout NetPrice( ) << endl;