690 likes | 702 Views
IT 240 Programming Paradigms. MS Information Technology Offshore Program Ateneo de Davao Session 3. Schedule this Weekend. Friday evening UML: Class Diagrams, Use Cases, Object Interaction Exercise Saturday Morning Group Exercise Design Patterns Saturday Afternoon Reports
E N D
IT 240Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3
Schedule this Weekend • Friday evening • UML: Class Diagrams, Use Cases, Object Interaction • Exercise • Saturday Morning • Group Exercise • Design Patterns • Saturday Afternoon • Reports • Final Exam? (Sunday morning?)
Class Diagrams Programming Paradigms
Classes in a Class Diagram • Class name only Example • With Details Example Bank Account Class Name Bank Account double balance deposit() withdraw() Class Name attributes methods
Relationships • Inheritance (arrow) • example: between Secretary and Employee • Composition/Aggregation (diamond) • example: between Car and Wheel • Association (line) • example: between Borrower and Book
Inheritance Employee public class Secretary extends Employee { … } Secretary
Composition/Aggregation Car Wheel 4 w[] public class Car { Wheel w[]; ... public Car() { w = new Wheel[4]; … } ... } Note: [ ] in diagram is sometimes left out since w does not need to be an array
Association Borrower Book 1 3 currBorr bk[] public class Borrower { Book bk[]; … public Borrower() { bk = new Book[3]; } } public class Book { Borrower currBorr; … }
Notational Details • Cardinality • Specifies the number of objects that may participate in the relationship • Roles and Navigability • Specifies relationship name and access • Aggregation versus Composition • Dependencies
Cardinality • Also known as multiplicity • Exact number (mandatory) • Range (e.g., 0..5) • * (many-valued) • Specifies the number of objects that may be associated with an object of the other class • For associations, multiplicity is specified on both participants
Roles and Navigability • Role name placed on the side of a participant • Let A and B be associated classes and let rrr be the role specified on B’s side • rrr is the role of B in the relationship • rrr is a member in class A • rrr refers to one or more (depending on multiplicity) B objects • An arrowhead indicates the ability to access B participant(s) from A
Uni-directional Navigability FastFood Counter PriceChecker getPrice() pc public class FastFoodCounter { PriceChecker pc; … public void add( … ) { … double pr = pc.getPrice(); … } … } public class PriceChecker { // no access to counter }
Bi-directional Navigability Borrower Book 0..3 0..1 currBorr bk[] public class Borrower { Book bk[]; … public Borrower() { bk = new Book[3]; } } public class Book { Borrower currBorr; … } Note: double arrowheads may be omitted (bi-directionalnavigability assumed)
Aggregation versus Composition • Part-of relationships • Aggregation • Part may be independent of the whole but the whole requires the part • Unfilled diamond • Composition (“stronger” form of aggregation) • Part is created and destroyed with the whole • Filled diamond • Definitions and distinctions between aggregation and composition still “under debate”
Mandatory Parts Car Wheel 4 wheels public class Car { private Wheel wheels[4]; // wheel objects are created externally ... public Car(Wheel w1, Wheel w2, … ) … // wheels required in constructor // w1, w2, … will be checked for null values }
Dependencies • Some classes use other classes but are not related to them in ways previously discussed • Not relationships in the sense that participants do not become attributes in another class • Most common example: • As local variables in (or arguments to) a method of the class
Dependency Example Restaurant processOrders() Parser getOrder() uses public class Restaurant { … public void processOrders() { Parser p = new Parser(…); // call getOrder() in this method } … }
Use Cases andObject Interaction Programming Paradigms
Depicting System Behavior • First, identify the use cases • Use case: typical interaction between a user and the system • Use Case Diagram • Depicts all use cases for a system • Interaction Diagram • Depicts a single use case as a collection of interacting objects
Example:Use Case Diagram LIBRARY SYSTEM Facilitate Checkout Search for Book Borrower Librarian Facilitate Return
Use Case Diagram Notation • Stick Figures – Actors • Could be a human user or a subsystem • Ellipses - Use Cases • Links - between actors and use cases • Links between use cases • <<uses>>: to depict inclusion of a use case • <<extends>>: to depict variations of a general use case
Example: <<uses>> Facilitate Checkout <<uses>> Log-in Librarian <<uses>> Facilitate Return Note: UML v.1.3 uses <<includes>> instead of <<uses>>
Example: <<extends>> By Author <<extends>> Search for Book query Borrower <<extends>> By Subject Note: query is called an extension point
Describing a Use Case • Narrative • Library example (Facilitate Checkout): Given a borrower’s ID Card and the book to be borrowed, the librarian enters the borrower’s ID number and the book’s catalogue number. If the borrower is allowed to check out the book, the system displays that the book has been recorded as borrowed • Or, an Interaction Diagram
Example:Interaction Diagram 2: checkIfAvailable() Checkout Screen :Book 1: checkIfDelinquent() 3: borrowBook() 4: setBorrower() :Borrower
Interaction (Collaboration) Diagram Notation • Rectangles: Classes/Objects • Arrows: Messages/Method Calls • Labels on Arrows • sequence number (whole numbers or X.X.X notation) • method name (the message passed) • more details, if helpful and necessary (iterators, conditions, parameters, types, return types)
Methods • Interaction Diagrams suggest/imply methods for classes • Has consequences on detailed class diagram • The label(s) of an arrow should be a method of the class the arrow points to • Library System • Borrower class should have at least two methods (checkIfDelinquent and borrowBook)
Including Conditionsand Types 2: avail = checkIfAvailable():boolean Checkout Screen b:Book 1: delinq = checkIfDelinquent():boolean 3:[!delinq & avail] borrowBook(Book b) 4: setBorrower( Borrower bk ) r:Borrower
Interaction Diagramsand Object-Oriented Code • Note correspondences between messages passed and method calls in actual code • Example: • borrowBook() is defined in Borrower and is called from the code in CheckOutScreen • setBorrower() is defined in Book and is called from borrowBook() method of Borrower • Other diagramming details imply if statements and loops in code
Creating an Object • new means a constructor is being called • Implies object creation 1: addCustomer(custdetails) :Encoder :CustomerList 2: new Note: this means theaddCustomer method willcontain code that createsa Customer object :Customer
Iteration • * is an iterator • means the method is called repeatedly 1: printSalesSummary() :Manager :Store 2: * getTotalSales() Note: Store needs data from all branches to produce a summary :Branch
Summary • Provide a Use Case Diagram to depict the use cases of a system • For each use case, describe and provide an Interaction Diagram • Depict use case as a collection of interacting objects • Other diagramming techniques that aid in building a dynamic model: • State diagram: describes object state changes • Activity diagram: describes method behavior
Design Patterns Programming Paradigms
Outline • Definition and Description of a Design Pattern • Discussion of Selected Patterns • Kinds of Patterns Reference: Gamma et al (“Gang-of-4”), Design Patterns
Pattern • Describes a problem that has occurred over and over in our environment, and then describes the core of the solution of that problem in a way that the solution can be used a million times over, without ever doing it in the same way twice.
Design Pattern • Solution to a particular kind of problem • How to combine classes and methods • Not solve every problem from first principles • Based on design experience • Use requires understanding of the appropriate problem and being able to recognize when such problems occur • Reuse solutions from the past
Describing a Pattern • Name • Intent/Problem • Situation (problem) and context • When to apply the pattern; conditions • Solution • Elements that make up the design, relationships, collaboration; more a template rather than a concrete solution • How the general arrangement of elements (classes and objects) solves it • UML diagrams (class relationships and responsibilities) and code implications
Describing a Pattern • Consequences • Results, variations, and tradeoffs • Critical in understanding cost/benefit
How Design Patterns Solve Design Problems • Finding appropriate objects • Determining object granularity • Specifying object interfaces • Specifying object implementations • Putting reuse mechanisms to work • Designing for change
How to use a design pattern • Read up on the pattern • Study structure, collaboration, participants • Look at sample code • Choose names of participants meaningful in the application context • Define classes • Define application specific names for operations in the process • Implement the operations
Selected Patterns for Discussion • Singleton • Factory Method • Composite • Iterator
Singleton • Intent • ensure a class has only one instance, and provide a global point of access to it • Motivation • Important for some classes to have exactly one instance. e.g., although there are many printers, should just have one print spooler • Ensure only one instance available and easily accessible • global variables gives access, but doesn’t keep you from instantiating many objects • Give class responsibility for keeping track of its sole instance
Design Solution • Defines a getInstance() operation that lets clients access its unique instance • May be responsible for creating its own unique instance Singleton static uniqueinstance Singleton data static getInstance() Singleton methods…
Singleton Example (Java) • Database public class Database { private static Database DB; ... private Database() { ... } public static Database getDB() { if (DB == null) DB = new Database(); return DB; } ... } Database static Database* DB instance attributes… static Database* getDB() instance methods… In application code… Database db = Database.getDB(); db.someMethod();
Singleton Example (C++) class Database { private: static Database *DB; ... private Database() { ... } public: static Database *getDB() { if (DB == NULL) DB = new Database()); return DB; } ... } Database *Database::DB=NULL; In application code… Database *db = Database.getDB(); Db->someMethod();
Implementation • Declare all of class’s constructors private • prevent other classes from directly creating an instance of this class • Hide the operation that creates the instance behind a class operation (getInstance) • Variation: Since creation policy is encapsulated in getInstance, possible to vary the creation policy
Singleton Consequences • Ensures only one (e.g., Database) instance exists in the system • Can maintain a pointer (need to create object on first get call) or an actual object • Can also use this pattern to control fixed multiple instances • Much better than the alternative: global variables • Permits refinement of operations and representation by subclassing
Abstract Factory • Intent: provide an interface for creating objects without specifying their concrete classes • Example: Stacks, Queues, and other data structures • Want users to not know or care how these structures are implemented (separation) • Example: UI toolkit to support multiple look-and-feel standards, e.g., Motif, PM • Abstract class for widget, supporting class for specific platform widget
Solutions in C++ • Use of header file (class declarations) and implementation file (method definitions) ok but limited • Header file usually contains private declarations which are technically part of the implementation • Change in implementation requires that the application using the data structure be recompiled • Alternative: create an abstract superclass with pure virtual data structure methods
Design Solution for Abstract Factory Factory createProduct() Product virtual methods Client ConcreteProdA methods ConcreteProdB methods Note: this is an abbreviated design