it 240 programming paradigms ms information technology offshore program ateneo de davao session 3

Post on 18-Jan-2018

219 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Class Diagrams Programming Paradigms

TRANSCRIPT

IT 240Programming Paradigms

MS Information Technology Offshore Program

Ateneo de DavaoSession 3

Schedule this WeekendFriday evening

UML: Class Diagrams, Use Cases, Object Interaction

ExerciseSaturday Morning

Group ExerciseDesign Patterns

Saturday AfternoonReportsFinal Exam? (Sunday morning?)

Class Diagrams

Programming Paradigms

Classes in a Class DiagramClass name only Example

With Details Example

Class Name

Class Nameattributesmethods

BankAccount

Bank Accountdouble balance

deposit()withdraw()

RelationshipsInheritance (arrow)

example: between Secretary and Employee

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

Association (line)example: between Borrower and Book

Inheritance

Secretary

Employee

public class Secretary extends Employee { …}

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

Association

Borrower BookcurrBorr bk[]

31

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

public class Book { Borrower currBorr; …}

Notational DetailsCardinality

Specifies the number of objects that may participate in the relationship

Roles and NavigabilitySpecifies relationship name and access

Aggregation versus CompositionDependencies

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

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

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}

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)

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”

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 }

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

Dependency Example

Parser

getOrder()

usesRestaurant

processOrders()

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

Use Cases andObject Interaction

Programming Paradigms

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

Example:Use Case Diagram

Facilitate Checkout

Facilitate Return

Search for Book

LIBRARY SYSTEM

BorrowerLibrarian

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

Example: <<uses>>

Facilitate Checkout

Facilitate Return

Librarian Log-in<<uses>>

<<uses>>

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

Example: <<extends>>

Search for Bookquery

Borrower

By Author

By Subject

<<extends>>

<<extends>>

Note: query iscalled anextension point

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

Example:Interaction Diagram

CheckoutScreen

:Borrower

:Book

1: checkIfDelinquent()3: borrowBook()

2: checkIfAvailable()

4: setBorrower()

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)

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)

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 )

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

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

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

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

Design Patterns

Programming Paradigms

OutlineDefinition and Description of a

Design PatternDiscussion of Selected PatternsKinds of Patterns

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

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.

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

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

Describing a PatternConsequences

Results, variations, and tradeoffsCritical in understanding cost/benefit

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

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

Selected Patterns for DiscussionSingletonFactory MethodCompositeIterator

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

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…

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

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

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

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

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

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

Design Solution for Abstract Factory

Factory

createProduct()

Product

virtual methods

ConcreteProdA

methods

ConcreteProdB

methods

Client

Note: this is anabbreviated design

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

ParticipantsClient

uses only interfaces declared by AbstractFactory and AbstractProduct classes

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

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

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”

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

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

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

*

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

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

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

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

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

ConsequencesSupports variations in the traversal

of an aggregateSimplifies the aggregate interfaceMore than one traversal can be

pending on one aggregate

Kinds of PatternsCreational

Object creation; e.g., Factory and Singleton

StructuralObject structure; e.g., Composite

BehavioralObject interaction and distribution of

responsibilities; e.g., Iterator

Creational PatternsAbstract FactoryBuilderFactory MethodPrototypeSingleton

Structural PatternsAdapterBridgeCompositeDecoratorFaçadeFlyweightProxy

Behavioral PatternsChain Of ResponsibilityCommandInterpreterIteratorMediatorMementoAnd a few more …

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

top related