Observer Pattern

Download Report

Transcript Observer Pattern

Lecture 4

   Unified Process   Disciplines Phases Requirements  Use case models UML     Use Case Diagrams Class Diagrams Sequence Diagrams Statechart Diagrams

Hat Problem

      Three persons each one wearing a hat that is either red or blue with 50% probability.

A person can see the colours of the other two hats but not its own colour.

Each player can either make no prediction or give a guess on the colour of its own hat.

The team wins if at least one player guessed correctly and no player guessed a wrong answer.

There is no form of communication between the players, in particular they do not know which decision any of the other players made.

The players can agree beforehand on a common fixed strategy.

Unified Process

    The UP describes work activities, such as writing a use-cas model, within disciplines. In the UP an artefact, is the general term for any work product, code, diagrams, models, database schema etc. .

There are several disciplines in the UP, business modeling, requirements, design, implementation, test, deployment, configuration and change management.

The course focuses on requirement analysis, design and implementation.

Unified Process

 UP Phases  Inception: approximate vision, business case, scope, vague estimates  inception = feasibility study Elaboration: refined vision, iterative implementation of the core architecture, resolution of high risks, identification of most requirements and scope   Construction: iterative implementation of the remaining lower risk and easier elements Transition: beta tests, deployment

Unified Process

Disciplines and phases: relative efforts UP disciplines Business modeling Require ments Design Inception Medium Medium Low Implemen tation Elaboration Construction Transition Medium High High Medium Low Medium High Medium

Unified Modeling Language

    UML a complete language for capturing knowledge (semantics) about a subject and expressing knowledge (syntax) regarding the subject.

Modeling involves a focus on understanding (knowing) a subject (system) and capturing and being able to communicate this knowledge.

UML is the result of unifying the information systems and technology industry´s best engineering practices (principles, techniques, methods and tools) UML is a notation not a method !!!

Unified Modeling Language

     UML is used for specification, visualization and documentation of systems UML is based on the object oriented paradigm UML applies to a multitude of different types of systems, domains and methods or processes.

UML unifies the syntax and semantics of methods and tools previously used for object oriented design UML was originally conceived by Rational Software Corporation and the ”Three Amigos” in 1995  Grady Booch   James Rumbaugh Ivar Jacobson

DIA

   DIA is a diagram creation program from Linkoeping University http://www.lysator.liu.se/~alla/dia/dia.html

It can be used to draw many different kinds of diagrams  Entity relationship diagrams   UML diagrams Flowcharts  Network diagrams It is available by adding the module dia

module add dia dia

Use Case Model

    Writing use cases is an excellent technique to understand and describe requirements.

A use case is a story of using the system.

The Unified Process defines the Use-Case Model within the requirements discipline.

The set of all Use-Cases provides a model of the system’s functionality and environment.

Use Cases

   An actor is something with behavior, such as a person (identified by a role), computer system or organization, for example a cashier.

A scenario is a specific sequence of actions and interactions between actors and the system under investigation, it is also called a use case instance, for example purchasing an item with cash.

A use case is a collection or related scenarios that describe actors using the system to support a goal.

Actors

    Actors are classes that define roles that objects external to a system may play. They are used to model users outside of a system that interact directly with the system as part of coherent work units. This includes human users and other systems Actors are characterized by their external view rather than their internal structure.

Actors participate in interactions involving message exchanges and actions with systems. Actors have goals to be achieved by interacting with the system.

Use Cases

    Uses cases are entities that define units of functionality or behavior provided by the system.

Use cases specify the external requirements of the system and the functionality offered by the system.

Use cases are

specified

by

sequence diagrams

representing the external interaction sequences among the systems and its actors.

Use cases are

realized collaboration diagrams

the system.

, or implemented, by representing the internal refinement of the services provided by

Use Cases

   When writing use cases you should ask the question: “How can using the system provide observable value to the user or fulfill their goals.” Use cases describe the functional requirements of a system, that indicate what the system is supposed to do.

Use cases are primarily text documents (written stories) although the may contain UML use case diagrams, to illustrate the names of use cases and actors and their relationship.

Use Cases

   Use cases describe the system as having responsibilities, they do not describe the internal workings of the system. They specify what the system must do (functional requirements) not how (design) it will do it.

Incorrect: The system writes the sale to a database.

Instead: The system records the sale.

Use Cases

 Formats for use cases    Brief : one-paragraph summary, usually of the main success scenario Casual : multiple paragraphs that cover various scenarios Fully dressed : elaborate description, all steps and variations are written in detail, there are supporting sections, such as pre conditions and success guarantees.

Use Cases

 Example (brief format): Borrow book : A library user arrives at the check-out with books to borrow. The patron identifies herself to the check-out system and the system validates that she is a legitimate user. The patron uses the check-out system to record each borrowed book. The system validates, records each book and associates the book with the patron. The system updates the library inventory. The patron receives a receipt from the system that states the books borrowed and the loan period.

Requirement Analysis

 Finding primary actors, goals and use cases   Choose the system boundary Identify the primary actors   Identify the goals of the actors Define uses cases that satisfy user goals

Use Cases

Borrow book : Primary actor : patron Stakeholders and Interests: -patron : Wants to borrow and return books quickly and with minimal effort. Wants receipt over borrowed and returned books. -librarian : Wants system to accurately record transactions. Wants fast access to and automatic update of library inventory. -library : Wants to reduce operation costs. Wants reliable capture of transactions.

Use Case Diagrams

   Use case diagrams render the user view of a system. Use case diagrams describe the functionality provided by the system or class to external actors. Use case diagrams contain    Actors Use cases Their relationships

Communicates Relationship

 Communicates relationships are associations between actors and use cases. They are used to model communications between actors and use cases in which an actor participates, communicates with, or takes part in a use case.

Borrow Items Return Items Patron Renew Items

Use Case Diagram

Patron Library system Borrow Items Return Items Renew Items Manage Catalog Manage Patrons Librarian

Borrow Items Use Case

 Detailing the functionality of the Borrow Item Use Case

Borrow Item Borrow Book Borrow Periodical Librarian Patron Borrow Electronic Media

Extends Relationships

  Extends relationships are generalizations between use cases. They are used to model relationships between use cases in which a base use case instance may include the behavior specified by an extending use case, subject to conditions specified in the extension. Extends relationships are used to capture exceptional behavior or variations of normal behavior.

Extends Relationships

 The arrow from the ”Pay by credit card” use case to the ”Purchase” use case is labeled with an <> stereotype to indicate that this use case is an option of the ”Purchase Item” use case

<> Pay by Credit card Customer Purchase Item <> Pay by Cheque

Uses Relationships

  Uses relationships are generalizations between use cases. They are used to model relationships between use cases in which a base use case instance will also include the behavior specified by a common use case.

Use relationships are used to share common behavior among use cases.

Uses Relationships

 The arrow from the ”Group Graphics” and ”Move Graphics” use case to the ”Select Graphics” use case is labeled with an <> stereotype to indicate that the ”Select Graphics” use case is included in the group and move skills.

Identify Patron Borrow Item <> Patron Renew Items <>

Unified Modeling Language

 UML object model describes the static structure of the problem domain, it contains  Class diagram describes the class attributes (name and type), operations and the relationship among classes. A class diagram contains classes and associations  Object diagram A class model describes all possible situation, whereas an object model describes a particular situation. An object diagram contains objects and links which represent the relationship between objects

Unified Modeling Language

 The UML dynamic model describes all temporal and dynamic aspects of the system, for example interaction among objects it contains  Sequence diagrams describe interactions among classes which are modeled as exchanges of messages. Sequence diagrams contain class roles, lifelines, activations and messages   Scenarios describe interactions among objects Statechart diagrams describe the states and responses of a class. They contain states and transitions.

Domain Model & Design Model

UML class, objects, sequence, statechart diagrams can be used during the OOA/D process for  Domain model :    Visual representation of conceptual classes or real world objects in a domain of interest.

A domain model is visualized by a set of class diagrams Design Model :  Describes how a particular use case is realized in terms of responsibilities and collaborations of objects.

UML Class Diagrams

 Class diagrams describe the static structure of a system rather than its behaviour. Class diagrams contain the following elements:  Domain objects or conceptual classes Which represent entities with common characteristics or features.   Attributes of conceptual classes Associations between conceptual classes

Class Diagram

Class name

Attribute ------------------------------ Operation

Account

account number balance ------------------------------ withdraw(amount) deposit(amount)

Room Booking System

   Develop a room reservation system that allows teachers to book lecture halls for their classes. Each reservation contains information about the room that is booked, the date, start and end time, class, the name of the person who booked the room and a unique booking number.

The reservation system maintains a list of lecture halls including their features such as name, location, size and number.

Class Diagram: Classes & Attributes

• conceptual classes • attributes of conceptual classes

Teacher

name position

Room

number seats room number name location

Booking

number start_time end_time

Course

name code

Room

Class Diagram Associations

gets booked by Booking 1 teaches Class *

Class Diagram: Associations

records reservation Teacher 1 teaches * enters Class

Multiplicity of Associations

Multiplicitly denotes how many objects of one class are associated with how many objects of the other class. The following symbols can be used to denote the multiplicity of a relationship      1 : exactly one object is involved in the relationship * : some objects are involved in the relationship 1..* : some objects but at least one 0..* : some objects but possibly zero 0,1 : zero or one object

Classes

Multiplicity of Associations

A 1 1 B A 1 * B A * * B A 1 0,1 B

Objects

:A :A :A :A :A :A :A :A :A :B :B :B :B :B :B :B :B :B

Association

One object uses another to help it carry out a task.

Classes that collaborate are usually related through associations. This type of relationship is also called a uses relationship.

Person

string name -------------------- ...

owns 1 * Car

string model int number -------------------- ...

Association Class

 An association class is a class that contains information about the relationship among other associated classes.

Person

string name int libraryid -------------------- ...

borrows * * Loan

date loan_date int loan_period bool returned -------------------- ...

Book

string title int isbnnumber -------------------- ...

Association Classes

customer number Supplier * supplies * part number buys from buys Part * * Customer * quantity / date

Higher Order Associations

Supplier Part Supplier 1 Order 1 Customer * 1 quantity /date Part * * * Order

----------------------------

quantity * 1 Customer

Multiple Associations

User

 Sometimes two classes are associated with each other in more than one way string name int uid -------------------- ...

accesses * owns 1 * * File

int size string name long index -------------------- ...

Self-Associations

 Sometimes a class is associated to itself as different objects play different roles

1 manager Employee * works for 1

string name string position -------------------- ...

* subordinate Company

string name string address -------------------- ...

Navigability

 An association can indicate the responsibility of the involved objects by an arrow that indicates the direction of the association. If navigability exists only in one direction we call the association uni directional otherwise bidirectional.

owns Person 1 * Cars

string name -------------------- ...

string type -------------------- ...

Aggregation

Aggregation means that one object contains other objects. Aggregation is also called part-of relationship.

Addressbook *

class Person { string name; ...} class Addressbook { Person[] persons; ... }

* Persons

Aggregation

Document 1 Figures * 1 * Paragraph 1

class Line { string text; ...} class Paragraph { Line[] lines; ... } class Figure { ...} class Document { Paragraph[] paragraphs; Figure[] figures; }

* Lines

Composition

Composition is building objects from parts. It is stronge type of aggregation in which the parts are necessary to the whole, namely they are permanently bound to the object and do not exist outside the object. Composition is ”is build of” relationship

Processor 1 Memory 1 CPU 1 1 I/O Port

Car

Generalization

Generalization is a relationship defined at the class level not the object level, which means that all objects of this class must obey the relationship. This is type of relationship is also called a is-a-kind-of relationship.

Vehicle

class Vehicle: class Car : public Vehicle class Truck : public Vehicle class MotorCycle : public Vehicle

Truck Motor Cycle

Sequence Diagrams

  Sequence diagrams describe interactions among classes. These interactions are modeled as exchanges of messages.

Sequence diagrams focus on classes and the messages they exchange to accomplish some desired behavior.

Sequence Diagrams

 Sequence diagrams are a type of interaction diagrams that contain  Class roles represent roles that objects may play within the interaction.

   Lifelines represent the existence of an object over a period of time.

Activations represent the time during which an object is performing an operation.

Messages represent communications between objects.

Sequence Diagram

 The interaction diagram illustrates the essential steps of playing, by sending messages to the instances of the

DiceGame

and

Die

classes.

play() :DiceGame roll() die 1 : Die die2 : Die fv1:=getFaceValue() roll() fv2:=getFaceValue()

Observer Sequence Diagram

ConcreteSubject Object

class role

ConcreteObserver ObjectA ConcreteObserver ObjectB

time

SetState()

activation

Notify()

lifeline

Update() GetState()

message

Update() GetState()

Observer Sequence Diagram

User EventHandler SelectGraphics() Draw() WindowManager MoveGraphics() Draw()

UML Statechart Diagrams

    Statechart diagrams lie within the behavioral view of a system and render the states and responses of a class.

Statechart diagrams describe the behaviour of a class in response to external stimuli.

Statechart diagrams describe the life cycle of an object.

Statechart diagrams contain   States Transitions

Finite State Machines (FSM)

  States   An FSM is exactly in one current state.

An FSM has an initial state.

 An FSM may change state due to a transition.

Transitions    Transitions connect states with each other.

Transitions carry a label or a guard condition that triggers the transition.

Transitions can be defined by a transition matrix.

FSM Example

   States : A,B,C, A is initial state Labels : 0,1 Transitions:   (A,0) -> B, (A,1) ->C, (B,0)-> B (B,1) -> C, (C,0) ->C, (C,1)-> B

0 B 0 A 1 1 1 C 0

FSM Example

    Input sequence: 011010 State sequence: A-B-C-B-B-C-C State B: even number of 1’s in sequence State C: odd number of 1’s in sequence

0 B 0 A 1 1 1 C 0

Statechart Diagrams

   States are classes that define status conditions that an object may satisfy during its existence.

States are used to model the situations during the life of an entity in which it satisfies some condition, performs some activity, or waits for some occurence.

An entity remains in a state for a finite and non instantaneous time.

Statechart Diagrams

  Transitions are associations between states. They are used to model relationships between the different states of an entity. An entity in one state will perform actions and possibly enter another state when an event occurs and a condition is satisfied (if specified), this occurence is known as the

firing

of a transition.

Statechart Diagrams

    Transitions are denoted as solid arrows between states and are labeled with a transition symbol.

Transitions relate source state and target state vertices.

Transitions may have square brackets containing a boolean guard condition that must be satisfied in order to enable the transition to fire.

Transitions may have a forward slash followed by one or more actions that result when the transition fires.

Statechart Diagram

Source State Event [Guard] / Action Target State

Example Statechart Diagram

initial pseudo state state

creation click event [outside object and not shift key] / delete from selected graphics Not Selected

transition guard

click event [inside object] / add to selected graphics Selected click event

action

[shift key pressed]

Hat Problem

    Simple strategy: Player A always guesses colour red, the other players make no guess. Probability of winning is 50%.

Common strategy: Players agree that when a player sees two hats with identical colours, then he guesses the opposite colour, if he sees two different colours he makes no guess. Chance of winning as a team is 75% 25% RRR, BBB: all three players guess wrong 75% RRB, RBR, RBB, BRB, BBR, BRR : one player guesses correctly, the other two players make no guess