Top Banner
IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3
69

IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Jan 18, 2018

Download

Documents

Job Wilkinson

Class Diagrams Programming Paradigms
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

IT 240Programming Paradigms

MS Information Technology Offshore Program

Ateneo de DavaoSession 3

Page 2: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Schedule this WeekendFriday evening

UML: Class Diagrams, Use Cases, Object Interaction

ExerciseSaturday Morning

Group ExerciseDesign Patterns

Saturday AfternoonReportsFinal Exam? (Sunday morning?)

Page 3: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Class Diagrams

Programming Paradigms

Page 4: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Classes in a Class DiagramClass name only Example

With Details Example

Class Name

Class Nameattributesmethods

BankAccount

Bank Accountdouble balance

deposit()withdraw()

Page 5: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

RelationshipsInheritance (arrow)

example: between Secretary and Employee

Composition/Aggregation (diamond)example: between Car and Wheel

Association (line)example: between Borrower and Book

Page 6: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Inheritance

Secretary

Employee

public class Secretary extends Employee { …}

Page 7: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Composition/Aggregation

Car Wheel4

w[]

public class Car { Wheel w[]; ... public Car() { w = new Wheel[4]; … } ...}

Note: [ ] in diagramis sometimes left outsince w does not needto be an array

Page 8: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Association

Borrower BookcurrBorr bk[]

31

public class Borrower { Book bk[]; … public Borrower() { bk = new Book[3]; }}

public class Book { Borrower currBorr; …}

Page 9: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Notational DetailsCardinality

Specifies the number of objects that may participate in the relationship

Roles and NavigabilitySpecifies relationship name and access

Aggregation versus CompositionDependencies

Page 10: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

CardinalityAlso 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

Page 11: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Roles and NavigabilityRole name placed on the side of a participantLet 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 objectsAn arrowhead indicates the ability to access

B participant(s) from A

Page 12: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Uni-directional Navigability

PriceChecker

getPrice()

pcFastFoodCounter

public class FastFoodCounter { PriceChecker pc; … public void add( … ) { … double pr = pc.getPrice(); … } …}

public class PriceChecker { // no access to counter}

Page 13: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Bi-directional Navigability

Borrower BookcurrBorr bk[]

0..30..1

public class Borrower { Book bk[]; … public Borrower() { bk = new Book[3]; }}

public class Book { Borrower currBorr; …}

Note: double arrowheads maybe omitted (bi-directionalnavigability assumed)

Page 14: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Aggregation versus Composition Part-of relationshipsAggregation

Part may be independent of the whole but the whole requires the part

Unfilled diamondComposition (“stronger” form of aggregation)

Part is created and destroyed with the wholeFilled diamond

Definitions and distinctions between aggregation and composition still “under debate”

Page 15: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Mandatory Parts

Car Wheel4

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 }

Page 16: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

DependenciesSome 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

Page 17: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Dependency Example

Parser

getOrder()

usesRestaurant

processOrders()

public class Restaurant { … public void processOrders() { Parser p = new Parser(…); // call getOrder() in this method } …}

Page 18: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Use Cases andObject Interaction

Programming Paradigms

Page 19: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Depicting System BehaviorFirst, identify the use cases

Use case: typical interaction between a user and the system

Use Case DiagramDepicts all use cases for a system

Interaction DiagramDepicts a single use case as a collection

of interacting objects

Page 20: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Example:Use Case Diagram

Facilitate Checkout

Facilitate Return

Search for Book

LIBRARY SYSTEM

BorrowerLibrarian

Page 21: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Use Case Diagram NotationStick Figures – Actors

Could be a human user or a subsystemEllipses - Use CasesLinks - between actors and use casesLinks between use cases

<<uses>>: to depict inclusion of a use case

<<extends>>: to depict variations of a general use case

Page 22: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Example: <<uses>>

Facilitate Checkout

Facilitate Return

Librarian Log-in<<uses>>

<<uses>>

Note: UML v.1.3uses <<includes>>instead of <<uses>>

Page 23: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Example: <<extends>>

Search for Bookquery

Borrower

By Author

By Subject

<<extends>>

<<extends>>

Note: query iscalled anextension point

Page 24: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Describing a Use CaseNarrative

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

Page 25: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Example:Interaction Diagram

CheckoutScreen

:Borrower

:Book

1: checkIfDelinquent()3: borrowBook()

2: checkIfAvailable()

4: setBorrower()

Page 26: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Interaction (Collaboration) Diagram NotationRectangles: Classes/ObjectsArrows: Messages/Method CallsLabels 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)

Page 27: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

MethodsInteraction Diagrams suggest/imply

methods for classesHas consequences on detailed class diagram

The label(s) of an arrow should be a method of the class the arrow points to

Library SystemBorrower class should have at least two

methods (checkIfDelinquent and borrowBook)

Page 28: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Including Conditionsand Types

CheckoutScreen

r:Borrower

b:Book

1: delinq = checkIfDelinquent():boolean3:[!delinq & avail] borrowBook(Book b)

2: avail = checkIfAvailable():boolean

4: setBorrower( Borrower bk )

Page 29: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Interaction Diagramsand Object-Oriented CodeNote correspondences between messages

passed and method calls in actual codeExample:

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

Page 30: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Creating an Objectnew means a constructor is being

calledImplies object creation

:Customer

:CustomerList

1: addCustomer(custdetails)

:Encoder

2: newNote: this means theaddCustomer method willcontain code that createsa Customer object

Page 31: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Iteration* is an iterator

means the method is called repeatedly

:Branch

:Store1: printSalesSummary()

:Manager

2: * getTotalSales()

Note: Store needsdata from all branchesto produce a summary

Page 32: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

SummaryProvide a Use Case Diagram to depict the use

cases of a systemFor each use case, describe and provide an

Interaction DiagramDepict use case as a collection of interacting

objectsOther diagramming techniques that aid in

building a dynamic model:State diagram: describes object state changesActivity diagram: describes method behavior

Page 33: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Design Patterns

Programming Paradigms

Page 34: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

OutlineDefinition and Description of a

Design PatternDiscussion of Selected PatternsKinds of Patterns

Reference: Gamma et al (“Gang-of-4”), Design Patterns

Page 35: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

PatternDescribes 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.

Page 36: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Design PatternSolution to a particular kind of problemHow to combine classes and methodsNot solve every problem from first principlesBased on design experienceUse requires understanding of the

appropriate problem and being able to recognize when such problems occur

Reuse solutions from the past

Page 37: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Describing a PatternNameIntent/Problem

Situation (problem) and contextWhen to apply the pattern; conditions

SolutionElements 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

Page 38: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Describing a PatternConsequences

Results, variations, and tradeoffsCritical in understanding cost/benefit

Page 39: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

How Design Patterns Solve Design ProblemsFinding appropriate objectsDetermining object granularitySpecifying object interfacesSpecifying object implementationsPutting reuse mechanisms to workDesigning for change

Page 40: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

How to use a design patternRead up on the patternStudy structure, collaboration, participantsLook at sample codeChoose names of participants meaningful

in the application contextDefine classesDefine application specific names for

operations in the processImplement the operations

Page 41: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Selected Patterns for DiscussionSingletonFactory MethodCompositeIterator

Page 42: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

SingletonIntent

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

Page 43: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Design SolutionDefines a getInstance() operation

that lets clients access its unique instance

May be responsible for creating its own unique instance Singleton

static uniqueinstanceSingleton data

static getInstance()Singleton methods…

Page 44: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Singleton Example (Java)Database

Database

static Database* DBinstance attributes…

static Database* getDB()instance methods…

public class Database {private static Database DB; ...private Database() { ... }public static Database getDB() { if (DB == null) DB = new Database(); return DB;} ...}

In application code…Database db = Database.getDB();db.someMethod();

Page 45: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

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();

Page 46: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

ImplementationDeclare 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

Page 47: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Singleton ConsequencesEnsures only one (e.g., Database) instance

exists in the systemCan maintain a pointer (need to create

object on first get call) or an actual objectCan also use this pattern to control fixed

multiple instancesMuch better than the alternative: global

variablesPermits refinement of operations and

representation by subclassing

Page 48: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Abstract FactoryIntent: provide an interface for creating

objects without specifying their concrete classes

Example: Stacks, Queues, and other data structuresWant 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, PMAbstract class for widget, supporting class for

specific platform widget

Page 49: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Solutions in C++Use of header file (class declarations) and

implementation file (method definitions) ok but limitedHeader file usually contains private declarations

which are technically part of the implementationChange in implementation requires that the

application using the data structure be recompiledAlternative: create an abstract superclass

with pure virtual data structure methods

Page 50: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Design Solution for Abstract Factory

Factory

createProduct()

Product

virtual methods

ConcreteProdA

methods

ConcreteProdB

methods

Client

Note: this is anabbreviated design

Page 51: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

ParticipantsAbstract Factory

declares an interface for operations that create abstract product objects

Concrete Factory implements the operations to create concrete

product objectsAbstract Product

declares an interface for a type of product objectConcrete Product

defines a product object to be created by the corresponding concrete factory

implements the abstract product interface

Page 52: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

ParticipantsClient

uses only interfaces declared by AbstractFactory and AbstractProduct classes

Page 53: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Stack Example (C++)Stack class defines virtual methods

push(), pop(), etc.ArrayStack and LinkedStack are derived classes

of Stack and contain concrete implementationsStackFactory class defines a createStack()

method that returns a ptr to a concrete stackStack *createStack() { return new ArrayStack(); }

Client programs need to be aware of Stack and StackFactory classes only No need to know about ArrayStack()

Page 54: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Factories in JavaStack is an InterfaceArrayStack and LinkedStack implement StackStackFactory returns objects of type Stack

through its factory methodsSelect class of the concrete factory it supplies to

client objectsIf using info from requesting client, can hardcode

selection logic and choice of factory objectsUse Hashed Adapter Pattern to separate selection logic

for concrete factories from the data it uses to make the selection

Page 55: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Abstract FactoryConsequencesFactory class or method can be altered

without affecting the applicationConcrete classes are isolated

Factory class can be responsible for creating different types of objectse.g., DataStructure factory that returns

stacks, queues, lists, etc. “product families”

Page 56: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Abstract Factory ConsequencesPromotes consistency among products

When products in a family are designed to work together, it is important that an application use objects from only one family at a time. This pattern enforces this.

Supporting new kinds of products is difficult requires extending the factory interface (fixed set)change AbstractFactory class and all the

subclasses

Page 57: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Composite PatternIntent: compose objects into tree

structures to represent (nested) part-whole hierarchiesClients treat individual objects and composition

of objects uniformlyExample: GUIs (e.g., java.awt.*)

Buttons, labels, text fields, and panels are VisualComponents but panels can also contain VisualComponent objects

Calling show() on a panel will call show() on the objects contained in it

Page 58: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Structure

+Operation()+Add(Component)()+Remove(Component)()+GetChild(int)()

Component

+Operation()()

Leaf +Operation()()+Add(Component)()+Remove(Component)()+GetChild(int)()

Composite

-End11

-End2*

-End31

-End4*

-End5

1

-End6

*Client

-End7

*-End8

*

Page 59: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

ParticipantsComponent

declares the interface for objects in the composition implements default behavior for interface common

to all classesdeclares interface for managing and accessing child

components (optional) defines interface for accessing a

component’s parent in the recursive structure Leaf

Leaf objects; primitives; has no childrendefine behavior for primitive objects

Page 60: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

ParticipantsComposite

Defines behavior of components having children

Stores child componentsImplements child-related operations in

the compositionClient

manipulates objects in the composition through the component interface

Page 61: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

ConsequencesDefines class hierarchies consisting

of primitive objects and composite objects

Easy to add new kinds of components

Simple client – can treat primitives and composites uniformly

Page 62: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Iterator PatternIntent: provide a way to access the

elements of an aggregate object sequentially without expressing its underlying representation

Example: iterators of C++ STL containersNote that you can have several iterator

objects for a container and that the iterators are separate classes

Page 63: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

MotivationTake responsibility for access and

traversal out of the container object and into an iterator or Cursor object

ExampleList

Count()Append(Element)Remove(Element)…

ListIterator

First()Next()IsDone()CurrentItem()

index

Page 64: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

ConsequencesSupports variations in the traversal

of an aggregateSimplifies the aggregate interfaceMore than one traversal can be

pending on one aggregate

Page 65: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Kinds of PatternsCreational

Object creation; e.g., Factory and Singleton

StructuralObject structure; e.g., Composite

BehavioralObject interaction and distribution of

responsibilities; e.g., Iterator

Page 66: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Creational PatternsAbstract FactoryBuilderFactory MethodPrototypeSingleton

Page 67: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Structural PatternsAdapterBridgeCompositeDecoratorFaçadeFlyweightProxy

Page 68: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Behavioral PatternsChain Of ResponsibilityCommandInterpreterIteratorMediatorMementoAnd a few more …

Page 69: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

SummaryMain point: to recognize that there are

proven solutions to problems that a designer/ programmer may encounterSolutions are results of others’ experiencesTowards “standard approaches”

Search for such solutions firstAlthough there is some merit attempting to

create the solution yourselfBecoming a design architect