IT 240 Programming Paradigms - PowerPoint PPT Presentation

About This Presentation
Title:

IT 240 Programming Paradigms

Description:

When products in a family are designed to work together, it is important that an ... Intent: compose objects into tree structures to represent (nested) part ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 70
Provided by: johnpaul3
Category:

less

Transcript and Presenter's Notes

Title: IT 240 Programming Paradigms


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

2
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?)

3
Class Diagrams
  • Programming Paradigms

4
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
5
Relationships
  • Inheritance (arrow)
  • example between Secretary and Employee
  • Composition/Aggregation (diamond)
  • example between Car and Wheel
  • Association (line)
  • example between Borrower and Book

6
Inheritance
Employee
public class Secretary extends Employee
Secretary
7
Composition/Aggregation
Car
Wheel
4
w
public class Car Wheel w ...
public Car() w new Wheel4
...
Note in diagram is sometimes left out since
w does not need to be an array
8
Association
Borrower
Book
3
1
currBorr
bk
public class Borrower Book bk
public Borrower() bk new Book3
public class Book Borrower currBorr
9
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

10
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

11
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 Bs 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

12
Uni-directional Navigability
PriceChecker getPrice()
FastFood Counter
pc
public class FastFoodCounter PriceChecker
pc public void add( )
double pr pc.getPrice()
public class PriceChecker // no access to
counter
13
Bi-directional Navigability
Borrower
Book
0..3
0..1
currBorr
bk
public class Borrower Book bk
public Borrower() bk new Book3
public class Book Borrower currBorr
Note double arrowheads may be omitted
(bi-directionalnavigability assumed)
14
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

15
Mandatory Parts
Car
Wheel
4
wheels
public class Car private Wheel wheels4
// wheel objects are created externally
... public Car(Wheel w1, Wheel w2, ) //
wheels required in constructor // w1, w2,
will be checked for null values
16
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

17
Dependency Example
Parser getOrder()
Restaurant processOrders()
uses
public class Restaurant public void
processOrders() Parser p new
Parser() // call getOrder() in this
method
18
Use Cases andObject Interaction
  • Programming Paradigms

19
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

20
ExampleUse Case Diagram
LIBRARY SYSTEM
Facilitate Checkout
Search for Book
Borrower
Librarian
Facilitate Return
21
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
  • ltltusesgtgt to depict inclusion of a use case
  • ltltextendsgtgt to depict variations of a general
    use case

22
Example ltltusesgtgt
Facilitate Checkout
ltltusesgtgt
Log-in
Librarian
ltltusesgtgt
Facilitate Return
Note UML v.1.3 uses ltltincludesgtgt instead of
ltltusesgtgt
23
Example ltltextendsgtgt
By Author
ltltextendsgtgt
Search for Book query
Borrower
ltltextendsgtgt
By Subject
Note query is called an extension point
24
Describing a Use Case
  • Narrative
  • Library example (Facilitate Checkout) Given a
    borrowers ID Card and the book to be borrowed,
    the librarian enters the borrowers ID number and
    the books 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

25
ExampleInteraction Diagram
2 checkIfAvailable()
Checkout Screen
Book
1 checkIfDelinquent() 3 borrowBook()
4 setBorrower()
Borrower
26
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)

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

28
Including Conditionsand Types
2 avail checkIfAvailable()boolean
Checkout Screen
bBook
1 delinq checkIfDelinquent()boolean 3!delinq
avail borrowBook(Book b)
4 setBorrower( Borrower bk )
rBorrower
29
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

30
Creating an Object
  • new means a constructor is being called
  • Implies object creation

1 addCustomer(custdetails)
CustomerList
Encoder
2 new
Note this means theaddCustomer method
willcontain code that createsa Customer object
Customer
31
Iteration
  • is an iterator
  • means the method is called repeatedly

1 printSalesSummary()
Store
Manager
2 getTotalSales()
Note Store needs data from all branches to
produce a summary
Branch
32
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

33
Design Patterns
  • Programming Paradigms

34
Outline
  • Definition and Description of a Design Pattern
  • Discussion of Selected Patterns
  • Kinds of Patterns
  • Reference Gamma et al (Gang-of-4), Design
    Patterns

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

36
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

37
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

38
Describing a Pattern
  • Consequences
  • Results, variations, and tradeoffs
  • Critical in understanding cost/benefit

39
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

40
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

41
Selected Patterns for Discussion
  • Singleton
  • Factory Method
  • Composite
  • Iterator

42
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 doesnt keep
    you from instantiating many objects
  • Give class responsibility for keeping track of
    its sole instance

43
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
44
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()
45
Singleton Example (C)
class Database private static Database
DB ... private Database() ...
public static Database getDB() if (DB
NULL) DB new Database())
return DB ... Database
DatabaseDBNULL
In application code Database db
Database.getDB() Db-gtsomeMethod()
46
Implementation
  • Declare all of classs 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

47
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

48
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

49
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

50
Design Solution for Abstract Factory
Factory createProduct()
Product virtual methods
Client
ConcreteProdA methods
ConcreteProdB methods
Note this is an abbreviated design
51
Participants
  • Abstract Factory
  • declares an interface for operations that create
    abstract product objects
  • Concrete Factory
  • implements the operations to create concrete
    product objects
  • Abstract Product
  • declares an interface for a type of product
    object
  • Concrete Product
  • defines a product object to be created by the
    corresponding concrete factory
  • implements the abstract product interface

52
Participants
  • Client
  • uses only interfaces declared by AbstractFactory
    and AbstractProduct classes

53
Stack Example (C)
  • Stack class defines virtual methods
  • push(), pop(), etc.
  • ArrayStack and LinkedStack are derived classes of
    Stack and contain concrete implementations
  • StackFactory class defines a createStack() method
    that returns a ptr to a concrete stack
  • Stack createStack() return new ArrayStack()
  • Client programs need to be aware of Stack and
    StackFactory classes only
  • No need to know about ArrayStack()

54
Factories in Java
  • Stack is an Interface
  • ArrayStack and LinkedStack implement Stack
  • StackFactory returns objects of type Stack
    through its factory methods
  • Select class of the concrete factory it supplies
    to client objects
  • If using info from requesting client, can
    hardcode selection logic and choice of factory
    objects
  • Use Hashed Adapter Pattern to separate selection
    logic for concrete factories from the data it
    uses to make the selection

55
Abstract FactoryConsequences
  • Factory class or method can be altered without
    affecting the application
  • Concrete classes are isolated
  • Factory class can be responsible for creating
    different types of objects
  • e.g., DataStructure factory that returns stacks,
    queues, lists, etc.
  • product families

56
Abstract Factory Consequences
  • Promotes 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

57
Composite Pattern
  • Intent compose objects into tree structures to
    represent (nested) part-whole hierarchies
  • Clients treat individual objects and composition
    of objects uniformly
  • Example 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

58
Structure
59
Participants
  • Component
  • declares the interface for objects in the
    composition
  • implements default behavior for interface common
    to all classes
  • declares interface for managing and accessing
    child components
  • (optional) defines interface for accessing a
    components parent in the recursive structure
  • Leaf
  • Leaf objects primitives has no children
  • define behavior for primitive objects

60
Participants
  • Composite
  • Defines behavior of components having children
  • Stores child components
  • Implements child-related operations in the
    composition
  • Client
  • manipulates objects in the composition through
    the component interface

61
Consequences
  • Defines class hierarchies consisting of primitive
    objects and composite objects
  • Easy to add new kinds of components
  • Simple client can treat primitives and
    composites uniformly

62
Iterator Pattern
  • Intent provide a way to access the elements of
    an aggregate object sequentially without
    expressing its underlying representation
  • Example iterators of C STL containers
  • Note that you can have several iterator objects
    for a container and that the iterators are
    separate classes

63
Motivation
  • Take responsibility for access and traversal out
    of the container object and into an iterator or
    Cursor object
  • Example

ListIterator
List
First() Next() IsDone() CurrentItem() index
Count() Append(Element) Remove(Element)
64
Consequences
  • Supports variations in the traversal of an
    aggregate
  • Simplifies the aggregate interface
  • More than one traversal can be pending on one
    aggregate

65
Kinds of Patterns
  • Creational
  • Object creation e.g., Factory and Singleton
  • Structural
  • Object structure e.g., Composite
  • Behavioral
  • Object interaction and distribution of
    responsibilities e.g., Iterator

66
Creational Patterns
  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton

67
Structural Patterns
  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Façade
  • Flyweight
  • Proxy

68
Behavioral Patterns
  • Chain Of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • And a few more

69
Summary
  • Main point to recognize that there are proven
    solutions to problems that a designer/ programmer
    may encounter
  • Solutions are results of others experiences
  • Towards standard approaches
  • Search for such solutions first
  • Although there is some merit attempting to create
    the solution yourself
  • Becoming a design architect
Write a Comment
User Comments (0)
About PowerShow.com