• 沒有找到結果。

UML and Patterns

N/A
N/A
Protected

Academic year: 2022

Share "UML and Patterns"

Copied!
10
0
0

加載中.... (立即查看全文)

全文

(1)

Chapter 12

UML and Patterns

Introduction to UML and Patterns Introduction to UML and Patterns

UML d f d i l h

• UML and patterns are two software design tools that  can be used within the context of any OOP language

UML i hi l l d f d i i d

• UML is a graphical language used for designing and  documenting OOP software

A i i i ki d f l

• A pattern in programming is a kind of template or  outline of a software task

A tt b li d diff t d i diff t b t

– A pattern can be realized as different code in different, but  similar, applications

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 12‐2

UML UML

P d d i f ti i

• Pseudocode is a way of representing a program in a  linear and algebraic manner

– It simplifies design by eliminating the details ofIt simplifies design by eliminating the details of  programming language syntax

• Graphical representation systems for program design 

h l b d

have also been used

Flowcharts and structure diagrams for example

U ifi d M d li L (UML) i t th

Unified Modeling Language (UML) is yet another  graphical representation formalism

– UML is designed to reflect and be used with the OOPUML is designed to reflect and be used with the OOP  philosophy

History of UML History of UML

A OOP h d l d diff h d l d

• As OOP has developed, different groups have developed  graphical or other representations for OOP design

• In 1996 Brady Booch Ivar Jacobson and James RumbaughIn 1996, Brady Booch, Ivar Jacobson, and James Rumbaugh  released an early version of UML

Its purpose was to produce a standardized graphical representation 

l f bj i d d i d d i

language for object‐oriented design and documentation 

• Since then, UML has been developed and revised in response  to feedback from the OOP community

to feedback from the OOP community

Today, the UML standard is maintained and certified by the Object  Management Group (OMG)

(2)

UML Class Diagrams UML Class Diagrams

Cl l OOP d h l di i

Classes are central to OOP, and the class diagram is  the easiest of the UML graphical representations to  understand and use

understand and use

• A class diagram is divided up into three sections

Th t ti t i th l

– The top section contains the class name

– The middle section contains the data specification for the  class

class

– The bottom section contains the actions or methods of the  class

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 12‐5

UML Class Diagrams UML Class Diagrams

Th d ifi i f h i f d i

• The data specification for each piece of data in a  UML diagram consists of its name,  followed by a  colon followed by its type

colon, followed by its type

• Each name is preceded by a character that specifies  its access type:

its access type:

– A minus sign (‐) indicates private access – A plus sign (+) indicates public access – A plus sign (+) indicates public access – A sharp (#) indicates protected access – A tilde (~) indicates package accessA tilde ( ) indicates package access

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 12‐6

UML Class Diagrams UML Class Diagrams

• Each method in a UML diagram is indicated by  the name of the method, followed by its  y

parenthesized parameter list, a colon, and its  return type

return type

• The access type of each method is indicated in 

h f

the same way as for data

UML Class Diagrams UML Class Diagrams

• A class diagram need not give a complete  description of the class p

– If a given analysis does not require that all the  class members be represented, then those class members be represented, then those  members are not listed in the class diagram Missing members are indicated with an ellipsis – Missing members are indicated with an ellipsis 

(three dots)

(3)

A UML Class Diagram A UML Class Diagram

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 12‐9

Class Interactions Class Interactions

R h h h j h i f f l l di

• Rather than show just the interface of a class, class diagrams  are primarily designed to show the interactions among classes

• UML has various ways to indicate the information flow fromUML has various ways to indicate the information flow from  one class object to another using different sorts of annotated  arrows

• UML has annotations for class groupings into packages, for  inheritance, and for other interactions

• In addition to these established annotations UML is

• In addition to these established annotations, UML is  extensible

12‐10 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Inheritance Diagrams Inheritance Diagrams

A i h it di h th l ti hi

An inheritance diagram shows the relationship  between a base class and its derived class(es)

– Normally only as much of the class diagram is shown as isNormally, only as much of the class diagram is shown as is  needed 

– Note that each derived class may serve as the base class of  its deri ed class(es)

its derived class(es)

• Each base class is drawn above its derived class(es)

– An upward pointing arrow is drawn between them to – An upward pointing arrow is drawn between them to 

indicate the inheritance relationship

A Class Hierarchy in UML Notation

(4)

Inheritance Diagrams Inheritance Diagrams

Th l h l i l i h d d fi i i

• The arrows also help in locating method definitions

• To look for a method definition for a class:

Examine the class definition first Examine the class definition first 

If the method is not found, the path of connecting arrows will show  the order and direction in which to search

i h l i di d b h i

Examine the parent class indicated by the connecting arrow

If the method is still not found, then examine this parent's parent class  indicated by the connecting arrow

Continue until the method is found, or until the top base class is  reached

12‐13 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Some Details of a UML Class Hierarchy

12‐14 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Patterns Patterns

Patterns are design outlines that apply across  a variety of software applications y pp

– To be useful, a pattern must apply across a variety  of situations

of situations

– To be substantive, a pattern must make some  assumptions about the domain of applications to assumptions about the domain of applications to  which it applies

Container Iterator Pattern Container‐Iterator Pattern

A i i l h h bj h ld

A container is a class or other construct whose objects hold  multiple pieces of data 

An array is a containerAn array is a container

Vectors and linked lists are containers

A String value can be viewed as a container that contains the  characters in the string

characters in the string

• Any construct that can be used to cycle through all the items  in a container is an iterator

An array index is an iterator for an array

The Container‐Iterator pattern describes how an iterator is 

(5)

Adaptor Pattern Adaptor Pattern

• The Adaptor pattern transforms one class into  a different class without changing the  g g

underlying class, but by merely adding a new  interface

interface

– For example, one way to create a stack data  structure is to start with an array then add the structure is to start with an array, then add the  stack interface

12‐17 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

The Model View Controller Pattern The Model‐View‐Controller Pattern

The Model‐View‐Controller pattern is a way of  separating the I/O task of an application from the  rest of the application

– The Model part of the pattern performs the heart of the  application

– The View part displays (outputs) a picture of the Model's  t t

state

– The Controller is the input part:  It relays commands from  the user to the Model

the user to the Model

12‐18 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

The Model View Controller Pattern The Model‐View‐Controller Pattern

h f h h i i i ll

• Each of the three interacting parts is normally  realized as an object with responsibilities for  its own tasks

• The Model‐View‐Controller pattern is an  p example of a divide‐and‐conquer strategy

– One big task is divided into three smaller tasks One big task is divided into three smaller tasks  with well‐defined responsibilities

The Model View Controller Pattern The Model‐View‐Controller Pattern

A l th M d l i ht b t i l

• As an example, the Model might be a container class,  such as an array.

• The View might display one element of the array

• The View might display one element of the array

• The Controller would give commands to display the  element at a specified index

element at a specified index

• The Model would notify the View to display a new 

element whenever the array contents changed or a 

different index location was given

(6)

The Model View Controller Pattern The Model‐View‐Controller Pattern

• Any application can be made to fit the Model‐

View‐Controller pattern, but it is particularly  p p y well suited to GUI (Graphical User Interface)  design projects

design projects

– The View can then be a visualization of the state  of the Model

of the Model

12‐21 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Model View Controller Pattern Model‐View‐Controller Pattern

12‐22 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

A Sorting Pattern A Sorting Pattern

Th ffi i i l i h ll

• The most efficient sorting algorithms all seem to  follow a divide‐and‐conquer strategy

Gi d i h h

• Given an array a, and using the < operator, these  sorting algorithms:

Di id th li t f l t t b t d i t t ll – Divide the list of elements to be sorted into two smaller 

lists (split)

– Recursively sort the two smaller lists (sort)Recursively sort the two smaller lists (sort)

– Then recombine the two sorted lists (join) to obtain the  final sorted list

A Sorting Pattern A Sorting Pattern

Th th d lit th l t i th i t l

• The method splitrearranges the elements in the interval  a[begin]through a[end]and divides the rearranged  interval at splitPoint

• The two smaller intervals are then sorted by a recursive call to  the method sort

• After the two smaller intervals are sorted the methodAfter the two smaller intervals are sorted, the method joinjoin combines them to obtain the final sorted version of the entire  larger interval

• Note that the pattern does not say exactly how the methods

• Note that the pattern does not say exactly how the methods  splitand joinare defined

Different definitions of splitand joinwill yield different sorting 

(7)

Divide and Conquer Sorting Pattern Divide‐and‐Conquer Sorting Pattern

12‐25 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Merge Sort Merge Sort

Th i l t li ti f thi ti tt i th

• The simplest realization of this sorting pattern is the  merge sort

• The definition of split is very simple

• The definition of  split is very simple

– It divides the array into two intervals without rearranging  the elements

• The definition of  join is more complicated

• Note:  There is a trade‐off between the complexity of 

h h d d

the methods  split and  join

– Either one can be made simpler at the expense of making  the other more complicated

the other more complicated

12‐26 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Merge Sort: the join method Merge Sort:  the join method

– The merging starts by comparing the smallest elements in  each smaller sorted interval

Th ll f th t l t i th ll t f ll th

– The smaller of these two elements is the smallest of all the  elements in either subinterval

The methodjoinmakes use of a temporary array and it – The method joinmakes use of a temporary array, and it 

is to this array that the smaller element is moved – The process is repeated with the remaining elements inThe process is repeated with the remaining elements in 

the two smaller sorted intervals to find the next smallest  element, and so forth

Merge Sort Code (1 of 3) Merge Sort Code (1 of 3)

/**

/

Class that realizes the divide-and-conquer sorting pattern and uses the merge sort algorithm.

*/

public class MergeSort {

{

/**

Precondition: Interval a[begin] through a[end] of a have elements.

Postcondition: The values in the interval have

been rearranged so that a[begin] <= a[begin+1] <= ... <= a[end].

*/

public static void sort(double[] a, int begin, int end) {

if ((end - begin) >= 1)g {

int splitPoint = split(a, begin, end);

sort(a, begin, splitPoint);

sort(a, splitPoint + 1, end);

join(a begin splitPoint end);

join(a, begin, splitPoint, end);

}//else sorting one (or fewer) elements so do nothing.

}

(8)

Merge Sort Code (2 of 3) Merge Sort Code (2 of 3)

private static int split(double[] a, int begin, int end) {

return ((begin + end)/2);g }

private static void join(double[] a, int begin, int splitPoint, int end) {

double[] temp;

double[] temp;

int intervalSize = (end - begin + 1);

temp = new double[intervalSize];

int nextLeft = begin; //index for first chunk

int nextRight = splitPoint + 1; //index for second chunk i i 0 //i d f

int i = 0; //index for temp

//Merge till one side is exhausted:

while ((nextLeft <= splitPoint) && (nextRight <= end)) {

if (a[nextLeft] < a[nextRight]) {

temp[i] = a[nextLeft];

i++; nextLeft++;

} }

else {

temp[i] = a[nextRight];

i++ tRi ht++

12‐29 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

i++; nextRight++;

} }

Merge Sort Code (3 of 3) Merge Sort Code (3 of 3)

while (nextLeft <= splitPoint)//Copy rest of left chunk, if any.

{ {

temp[i] = a[nextLeft];

i++; nextLeft++;

}

hil ( tRi ht < d) //C t f i ht h k if while (nextRight <= end) //Copy rest of right chunk, if any.

{

temp[i] = a[nextRight];

i++; nextRight++;

}

for (i = 0; i < intervalSize; i++) a[begin + i] = temp[i];

} }

12‐30 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Merge Sort Demo Merge Sort Demo

public class MergeSortDemo {

public static void main(String[] args) {

{

double[] b = {7.7, 5.5, 11, 3, 16, 4.4, 20, 14, 13, 42};

System.out.println("Array contents before sorting:");

int i;

for (i = 0; i < b.length; i++) System.out.print(b[i] + " ");

System.out.println( );

MergeSort.sort(b, 0, b.length-1);g ( , , g );

System.out.println("Sorted array values:");

for (i = 0; i < b.length; i++) System.out.print(b[i] + " ");

Quick Sort Quick Sort

I h i k li i f h i

In the quick sort realization of the sorting pattern,  the definition of  split is quite sophisticated, while  join is utterly simple

join is utterly simple

First, a value called the splitting value is chosen

We do this arbitrarily but other methods to select this value mayWe do this arbitrarily but other methods to select this value may  be employed

– The elements in the array are rearranged: 

All elements less than or equal to the splitting value are placed at  the front of the array

(9)

Quick Sort Quick Sort

N t th t th ll l t t t d d

• Note that the smaller elements are not sorted, and  the larger elements are not sorted

– However all the elements before the splitting value areHowever, all the elements before the splitting value are  smaller than any of the elements after the splitting value

• The smaller elements are then sorted by a recursive 

ll h l l

call, as are the larger elements

• Then these two sorted segments are  combined

Th j i h d ll d hi

– The joinmethod actually does nothing

12‐33 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Quick Sort Code (1 of 3) Quick Sort Code (1 of 3)

public class QuickSort {

/**

Precondition: Interval a[begin] through a[end] of a have elements.

Postcondition: The values in the interval have

been rearranged so that a[begin] <= a[begin+1] <= ... <= a[end].

*//

public static void sort(double[] a, int begin, int end) {

if ((end - begin) >= 1) {

int splitPoint = split(a begin end);

int splitPoint = split(a, begin, end);

sort(a, begin, splitPoint);

sort(a, splitPoint + 1, end);

join(a, begin, splitPoint, end);

}//else sorting one (or fewer) elements so do nothing.

}

private static int split(double[] a, int begin, int end) {

double[] temp;[] p;

int size = (end - begin + 1);

temp = new double[size];

double splitValue = a[begin];

int up = 0;

12‐34 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

int up = 0;

int down = size - 1;

Quick Sort Code (2 of 3) Quick Sort Code (2 of 3)

//Note that a[begin] = splitValue is skipped.

for (int i = begin + 1; i <= end; i++) {

{

if (a[i] <= splitValue) {

temp[up] = a[i];

up++;

} else {

temp[down] = a[i];

down--;

} }

//0 <= up = down < size

temp[up] = a[begin]; //Positions the split value, spliV.

//temp[i] <= splitValue for i < up // temp[up] = splitValue

// i i i

// temp[i] > splitValue for i > up for (int i = 0; i < size; i++)

Quick Sort Code (3 of 3) Quick Sort Code (3 of 3)

private static void join(double[] a, int begin,

i i i i

int splitPoint, int end) {

//Nothing to do.

} }

public class QuickSortDemo {

public static void main(String[] args) public static void main(String[] args) {

double[] b = {7.7, 5.5, 11, 3, 16, 4.4, 20, 14, 13, 42};

System.out.println("Array contents before sorting:");

i t i int i;

for (i = 0; i < b.length; i++) System.out.print(b[i] + " ");

System.out.println( );

QuickSort.sort(b, 0, b.length-1);

System.out.println("Sorted array values:");

(10)

Restrictions on the Sorting Pattern Restrictions on the Sorting Pattern

Lik ll h i h i i

• Like all patterns, the sorting pattern has some restrictions on  where it applies

It applies only to types for which the <t app es o y to types o c t e operator is definedope ato s de ed It applies only to sorting into increasing order

• The pattern can be made more general, however

The <operator can be replaced with a booleanvalued method  called compare

The comparep method would take two arguments of the base type of g yp the array, and return trueor falsebased on the comparison  criteria

12‐37 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Efficiency of the Sorting Pattern Efficiency of the Sorting Pattern

Th ffi i i l i f h i

• The most efficient implementations of the sorting  pattern are those for which the  split method  divides the array into two substantial size chunks divides the array into two substantial size chunks

– The merge sort splitdivides the array into two roughly  equal parts, and is very efficient

equal parts, and is very efficient

– The quick sort splitmay or may not divide the array into  two roughly equal parts

When it does not, its worst‐case running time is not as fast as that  of merge sort

12‐38 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.

Efficiency of the Sorting Pattern Efficiency of the Sorting Pattern

• The selection sort algorithm (from Chapter 5)  divides the array into two pieces:  one with a  y p single element, and one with the rest of the  array interval

array interval

– Because of this uneven division, selection sort has  a poor running time

a poor running time – However, it is simple

Pragmatics and Patterns Pragmatics and Patterns

P id i

• Patterns are guides, not requirements

– It is not necessary to follow all the fine details

l k d b d b f ll

• For example, quick sort was described by following  the sorting pattern exactly

N i h d i h f h h d ll i

– Notice that, despite the fact that method calls incur  overhead, the quick sort joinmethod does nothing – In practice calls toIn practice calls to joinjoinwould be eliminatedwould be eliminated

– Other optimizations can also be done once the general  pattern of an algorithm is clear

參考文獻

相關文件

(Note that the representation theorem concludes that each one linear transformation can be represented by a unique matrix up to the. considering

Furthermore, paragraph 3 has already given WTO Members specific instructions regarding criteria, in addition to those listed in WT/L/161, for granting observer status of

The hashCode method for a given class can be used to test for object equality and object inequality for that class. The hashCode method is used by the java.util.SortedSet

With a “multi-pronged and co-ordinated” approach, the Education Bureau (EDB) adopts a wide array of measures, which includes providing curriculum guides, developing learning

Analogous to the additional properties that ψ YF (given as (9)-(10)) possesses and as will be seen in Sec. 4, if F is strongly monotone [7] then f provides a global error bound

• is free and does not change the value of action, and then using the traceless condition can be satisfied without breaking the condition (i) and (ii)... We then compute

(ii) If we have to count those permutations in which no vowels can be together, we first have to find all possible arrangements of 8 letters taken all at a time, which can be done

• When a number can not be represented exactly with the fixed finite number of digits in a computer, a near-by floating-point number is chosen for approximate