Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
C HAPT E R 3 Chapter 8 Data Abstractions J. Glenn Glenn Brookshear Brookshear J. 蔡文能 1 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-1 Chapter 8: Data Abstractions • • • • • • 8.1 Data Structure Fundamentals 8.2 Implementing Data Structures 8.3 A Short Case Study 8.4 Customized Data Types 8.5 Classes and Objects 8.6 Pointers in Machine Language – See the Assembly code: tcc -S file.c gcc -S file.c g++ -S file.cpp 2 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-2 Basic Data Structures • Homogeneous array – Row major: Pascal, C/C++, Java, C# – Column major: FORTRAN • Heterogeneous array: struct/class [, union] • Sequence – List : ArrayList, LinkedList – Stack (in Java, a Stack is a Vector) – Queue • Tree Data Structures: How to arrange data in memory 3 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-3 Arrays vs. Struct (including class) • Homogeneous arrays – Row-major order versus column major order – Address polynomial for each of them • Heterogeneous arrays (class, struct) – Components can be stored one after the other in a contiguous block – Components can be stored in separate locations identified by pointers Give a formula for finding the entry in the i-th row and the j-th column of a two-dimensional array if it is stored in column major order rather than row major order. 4 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-4 Array allocation: Row major vs. Column major • Column major (column by column) – FORTRAN: integer*4 m(3,6) 在 2010 在 2014 1 2 3 4 5 6 1 0 2 1 3 2 FORTRAN 用小括號 • Row major (row by row) – Pascal, C/C++,Java – int m[3][6]; – Subscript 從 0 開始 m(2,4) 在 何位址? m[1][3]在 何位址? 6 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-6 Column-major order (FORTRAN) The array is stored as a sequence of arrays consisting of columns (column by column) Integer*4 M(2,7) 1 1 2 3 4 5 6 7 M(1,1) M(2,1) M(1,2) M(1,2) 2 x(2,4) 7 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-7 Figure 8.6 A two-dimensional array with four rows and five columns stored in row major order 須知道每列(row)有幾欄(column) 才能算出下列從何處開始安排 Give a formula for finding the entry in the i-th row and the j-th column of a two-dimensional array if it is stored in column major order rather than row major order. 8 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-8 Row-major order: Pascal, C/C++, Java,C# The array is stored as a sequence of arrays consisting of rows (row by row) int x[2][7]; // declare as 2 rows x 7 columns x 0 0 1 1 2 3 4 5 6 X[0][1] X[0][0] X[0][1] X[0][2] X[1][3] * 在我之前有幾個元素 ? * 每個元素佔幾個 address? (現代電腦大多一byte一個address) 9 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-9 Accessing elements in 2D arrays (1/2) int x[m][n]; m, n should be constant in most languages m=number of rows 通常用 u=0, v=0 n=number of columns b=address of x[u][v] Address of x[i][j] (row major order) is b + ((i-u)*n + j-v) * (size of entry) 寫個C/C++小程式然後 gcc -S file.c 或 g++ -S file.cpp 編譯成 Assembly code 研究 Brookshear page 306 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 10 Slide 8-10 Accessing elements in 2D arrays (2/2) The formula for finding the address of an element is i = b + s*n s*n e k n’ = = = = s*e*k + s*n’ = s*(e*k + n’) number of elements in a row or column number of rows or columns to be skipped the number of elements between the target element and the beginning of a row or column where b = base address s = size of each element n = the number of elements between the target element and the base address * 在我之前有幾個元素 ? * 每個元素佔幾個 address? (現代電腦大多一byte一個address) 11 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-11 e*k + n’ = 6 skip 6 elements Example Row-major order: e = 4, k = 1, n’ = 2 Column-major order: e = 3, k =2, n’ = e*k + n’ = 7 skip 7 elements 1 在 我 之 前 有 6 個 在我之前有 7 個 0 1 2 0 Base address 3 target element 1 2 Copyright © 2009 Pearson Education, Inc. 12 交大資工 蔡文能 計概 Slide 8-12 Dynamic Array ? • Most Languages do NOT support dynamic array Use pointer in C/C++ int *p; p = new int[ numberOfElementsNeeded ]; Q: C++ STL 的 vector 如何“自動長大” ? In Java, array is an object; create it dynamically! int p[ ]; // p is only a reference p = new int[ numberOfElementsNeeded ]; 13 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-13 Represent the data and Store the data Primitive data: (大部份電腦用硬體就可處理的) bit, byte, word, double word, quad word C: char, short, int, long, float, double, [long double], and pointer of any data type C++: bool, + ALL types in C Java: boolean, byte, char(16 bits), short(16 bits) int(32 bits), long(64 bits), float(32 bits), double(64 bits) Abstract data (User defined data type): List, Deque, Stack, Queue, Tree, … 15 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-15 結構與型別 (如何自定資料結構?) solution: struct • 只能用前述基本 data type 嗎? • User defined data type? •考慮寫程式處理全班成績資料, 包括加總平 均並排序(Sort)然後印出一份照名次排序的 以及一份照學號排序的全班資料 –如何做 Sort (排序) ? –Sort 時兩學生資料要對調, 要如何對調? –有很多 array ? 存學號的 array, 存姓名的 array? 存成績的 array? … Bubble sort, Insertion sort, Selection sort Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 16 Slide 8-16 So, Why using struct in C ? Why using class in C++ ? • Struct 可以把相關資料 group 在一起 struct student x[99], tmp; /* … */ tmp = x[i]; x[i] = x[k]; x[k] = tmp; • • • • 增加程式可讀性 程式更容易維護 其實都不用到 struct 也能寫出所有程式! How to define / use struct ? – Next slides User defined data type is a template for a heterogeneous structure 17 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-17 User-defined Data Type #include <stdio.h> 考慮寫個程式處理學生的成 績資料, 如何表示一個學生的 struct Student { 資料? 想一想. . . long sid; char name[9]; /*可存四個Big5中文 */ float score[13]; /*每人最多修13 科 */ }; /*注意struct與class之 分號不能省掉*/ 習慣上第一個字母大寫 int main( ) { struct Student x; /* C++ 和 C99 不用寫 struct */ x.sid = 123; /* dot notation */ strcpy(x.name, "張大千") ; /*注意字串不能= */ /* 用 loop 把成績讀入 x.score[?] */ 18 } //C 的字串不能直接用 = 複製! 也可用 memcpy( ) Copyright © 2009 Pearson Education, Inc. Slide 8-18 交大資工 蔡文能 計概 Dynamic Data Structures • Static Data Structures: Size and shape of data structure does not change • Dynamic Data Structures: Size and shape of data structure can change at Run time (How?) • Pointers: An integer which is a memory address points to some data unit. For example: the program counter in the CPU. (Intel CPU uses CS:IP) x pointer 6087 The pointer points to memory cell x which contains the value 6087. Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 19 Slide 8-19 Sequence • A group of elements in a specified order is called a sequence. • A tuple is a finite sequence. – Ordered pair (x, y), triple (x, y, z), quadruple, and quintuple – A k-tuple is a tuple of k elements. • List, Stack, Queue , Deque, Vector all are sequence data structures that their size may vary. 20 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-20 Figure 8.1 Lists, stacks, and queues C++ STL, Java 都有提供 iterator 可走遍整個資料結構 An iterator is an object that enables a user to loop through a collection without accessing the collection’s fields. 21 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-21 Lists • A list is a collection of entries that appear in sequential order. • Can be an ArrayList or be a LinkedList. – ArrayList: List stored in a homogeneous array; also known as Contiguous list – LinkedList: List in which each entries are linked by pointers • Head pointer: Pointer to first entry in list • NIL pointer: A “non-pointer” value used to indicate end of list (NULL or 0) • List in C++ STL vs. List in Java – In C++ STL, list is a template class which implements as a linked list – In Java, java.util.List is a interface which extends from java.util.Collection interface; java.util.ArrayList and java.util.LinkedList both implements List interface and thus they are both Lists. 22 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-22 ArrayList -Contiguous Storage of a List • List entries are stored consecutively in memory : ArrayList • Advantage: simple, quick random access • Disadvantage: insertion and deletion difficult. Java.util.ArrayList is NOT a Queue because it does NOT implement java.util.Queue interface; However, java.util.LinkedList is a Queue and thus the following statement is correct: Queue<Integer> gg = new LinkedList<Integer> ( ); 23 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-23 Linked Lists Each list entry contains a pointer to the next entry List entries can be stored in any part of memory. There is a special head pointer for the first entry and a Nil pointer in the last entry. java.util.LinkedList is a Queue and thus the following statement is correct: Queue<Integer> gg = new LinkedList<Integer> ( ); However, the following is WRONG ! Queue<Integer> gg = new ArrayList<Integer> ( ); // wrong In JDK 1.5, LinkedList implements Queue; In JDK 1.6, it implements Deque which extends Queue Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 24 Slide 8-24 Figure 8.9 The structure of a linked list Singly LinkedList Java 的 LinkedList 與 C++ STL 的 list 都是doubly linked list 25 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-25 Figure 8.10 Deleting an entry from a linked list Singly LinkedList Figure 8.11 Inserting an entry into a linked list 26 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-26 Inserting an entry into a doubly linked list head p 共有四個 Link 要改 ! Add before this node head What about delete ? Copyright © 2009 Pearson Education, Inc. tmp 交大資工 蔡文能 計概 p 27 Slide 8-27 Stacks • A stack is a list in which all deletions and insertions occur at the same end. • Alternative name: LIFO structure – Last In First Out • Top: place where insertions and deletions occur. • Base: opposite end to the top. • Insertion=push, deletion = pop. A stack in memory 28 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-28 Stacks and Procedures/Functions Call When a procedure P is called a pointer to the return location is pushed onto a stack. If a second procedure Q is called from P then a pointer to the return location for Q is pushed onto the same stack. When a procedure finishes, the return location is popped from the stack. tcc –S filename.c tcc –S filename.cpp gcc –S filename.c g++ –S filename.cpp 注意gcc/g++ 翻譯出的 組合語言格式與 Intel 公佈的或 是Microsoft MASM 格式不同! 除了指令名稱略不同外, 指令中運算元(operands)的 左右順序相反! 29 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-29 C++ STL stack contains a deque [, vector, list ] template <class T, class T38=deque<T> > class stack { protected: T38 c; // the actual data is here public: typedef typename T38::value_type value_type; typedef typename T38::reference reference; typedef typename T38::const_reference const_reference; stack( ):c( ) { } explicit stack(const T38& seq) : c(seq) { } bool empty( ) const { return c.empty( ); } int size( ) const { return c.size ( ); } reference top( ) { return c.back( ); } const_reference top( ) const { return c.back( ); } void push(const value_type& x) { c.push_back(x); } void pop( ) { c.pop_back( ); } }; // class stack stack<int> gg; stack<int, vector<int> > yy; Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 30 Slide 8-30 Stack in java.util.*; package java.util; public class Stack<E> extends Vector<E> { public Stack() { } public boolean empty() { return size( ) == 0; } public E push(E item) { addElement(item); return item; } public synchronized E pop( ) { E obj; int len = size( ); obj = peek( ); removeElementAt(len - 1); return obj; } public synchronized E peek( ) { int len = size( ); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size( ) - i; } return -1; } private static final long serialVersionUID = 1224463164541339165L; } // class Stack 31 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-31 Vector in java.util.*; package java.util; public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { protected Object[ ] elementData; // Java 的參考是類似C 的指標 protected int elementCount; protected int capacityIncrement; // if 0, double the capacity (array length) private static final long serialVersionUID = -2767605614048989439L; public Vector(int initialCapacity, int capacityIncrement) { super( ); // invoke constructor of my father if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; } public Vector(int initialCapacity) { // default increment 0 will double capacity this(initialCapacity, 0); } public Vector( ) { this(10); } // Default capacity is 10 public synchronized int size( ) { return elementCount; } // . . . 32 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-32 Stack 應用 again • 使用堆疊把 infix postfix – Stack 內放運算符號和左括號, 注意優先權 – Operand 直接輸出 • 使用堆疊計算 postfix 的答案 – Stack 內放 operand 值 (value, 整數或實數) – 遇到 operator 就把 operand pop出來算 – 算出的 value 再 push 進去 33 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-33 Handling Pointers struct Student { long x; struct Student * next; }; struct Student * p; p long x next Assign the value 4 to x: p->x = 4; // C, C++ p.x = 4; // Java, C# Initialise a pointer q to point to the next item: q = p->next; // C, C++ q = p.next; // Java 34 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-34 Figure 8.19 A procedure for printing a linked list 35 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-35 Print a Linked List in Reverse Order Procedure reverseprint(L) p = head(L) While p<>Nil do push(p.data, stack) p=p.next EndWhile While stack not empty Print(pop(stack)) EndWhile End Procedure 36 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-36 Queue • A queue is a list in which insertions are performed at one end (tail) and deletions are performed at the opposite end (head). • FIFO: First In, First Out tail: insertions tail pointer: to next unused location head: deletions head pointer: to head item 37 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-37 Circular Queue empty vs. full EMPTY QUEUE [3] [2] [2] [3] J2 [1] [4] [0] J3 [1] J1 [5] [4] [0] front = 0 rear = 0 [5] front = 0 rear = 3 What if Queue is full ? 40 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-40 Leave one empty space when Queue is full Why? FULL QUEUE FULL QUEUE [2] [3] J2 [1] [2] [3] J8 J3 J9 J4 [4][1] J7 J1 J5 [0] [5] front =0 rear = 5 How to test when queue is empty? How to test when queue is full? Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 [4] J6 [0] J5 [5] front =4 rear =3 41 Slide 8-41 Enqueue in a Circular Queue void enqueue(int front, int *rear, element item) { /* add an item to the queue */ *rear = (*rear +1) % MAX_QUEUE_SIZE; if (front == *rear) /* reset rear and print error */ return; } queue[*rear] = item; } 42 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-42 Dequeue from Circular Queue element dequeue(int* front, int rear) { element item; /* remove front element from the queue and put it in item */ if (*front == rear) return queue_empty( ); /* queue_empty returns an error key */ *front = (*front+1) % MAX_QUEUE_SIZE; return queue[*front]; } 43 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-43 Trees Earth Europe UK Africa Asia France Chad China Paris Beijing London S. America India Peru N. America USA Lima 44 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-44 Figure 8.2 An example of an organization chart 45 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-45 Definition of a Tree • A tree is a connected undirected graph in which there are no circuits. • A rooted tree is a tree in which one node is selected as the root. • In computing, trees are usually rooted. 46 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-46 Terminology • • • • • Node, root, leaf, terminal node, parent, child. Ancestor: Parent, parent of parent, etc. Descendent: Child, child of child, etc. Siblings: Nodes sharing a common parent Subtree: a node together with all the nodes below it. • Depth: number of nodes on longest path from root to a leaf. • Binary tree: each node has at most two children. 47 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-47 Figure 8.3 Tree terminology 48 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-48 Binary Trees • A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree. • Any tree can be transformed into binary tree. – by left child-right sibling representation • The left subtree and the right subtree are distinguished. 49 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-49 Samples of Binary Trees Complete Binary Tree B B B 3 D C E G F 4 4 E A 2 Skewed Binary Tree 歪斜樹 C D 1 A A H I 5 What is a Full Binary Tree ? Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 50 Slide 8-50 Figure 8.16 The conceptual and actual organization of a binary tree using a linked storage system 51 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-51 Figure 8.17: A tree stored without pointers 適合大部份 node 都存在的 tree : complete tree, full tree 52 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-52 Figure 8.18: A sparse, unbalanced tree shown in its conceptual form and as it would be stored without pointers 大部份空間都浪費掉了! Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 53 Slide 8-53 Recursive Printing of a Binary Tree Procedure printTree(tree) If (tree not empty) printTree(left subtree) print(root) printTree(right subtree) EndIf EndProcedure In-order, pre-order, post-order traversal 54 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-54 A procedure for printing the data in a binary tree (pre-order Traversal) void printTree(Node root) { if(root != NULL ) { printTheRoot(root); printTree(root.left); printTree(root.right); } } 55 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-55 A procedure for printing the data in a binary tree (post-order Traversal) void printTree(Node root) { if(root != NULL ) { printTree(root.left); printTree(root.right); printf(root.data); } } 56 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-56 Inserting the entry M into the list B, E, G, H, J, K, N, P stored as a binary search tree 57 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-57 A procedure for inserting a new entry in a list stored as a Binary Search Tree 58 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-58 Representation of Trees (1/2) • List Representation – ( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) ) – The root comes first, followed by a list of sub-trees data link 1 link 2 ... link n How many link fields are needed in such a representation? 59 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-59 Representation of trees (2/2) data left child right sibling A F E K D C B G H I J M L 60 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-60 Binary tree representation of tree Left Child - Right Sibling data left child right sibling A F E K D C B G H I J M L 61 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-61 Left child-right child tree representation of a tree A B C E F K D G H L M 往右下角拉 I J Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 62 Slide 8-62 Abstract Data Type (ADT) • A user-defined data type with procedures/functions for access and manipulation • Abstract Data Type in Object Oriented Languages has these features: – Characteristics can be inherited – Contents can be encapsulated – Constructor methods to initialize new objects • To define an ADT – C++: struct, class – Java, C#: class 把 data 以及對 該些 data 有關的方法(method)或稱函數(function, 函式)) 封裝(encapsulate)在一個程式單元(例如class)內方便使用 Why using Class? Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 63 Slide 8-63 ADT --- Data Abstraction • An Abstract Data Type (ADT) is a user-defined data type that satisfies the following two conditions: (Encapsulation + Information Hiding) – The representation of, and operations on, objects of the type are defined in a single syntactic unit; also, other program units can create objects of the type. – The representation of objects of the type is hidden from the program units that use these objects, so the only operations (methods) possible are those provided in the type's definition which are known as interfaces. 64 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-64 What does Abstraction mean? • Abstraction means ignoring irrelevant features, properties, or functions and emphasizing the relevant ones... “Relevant” to what? • ... relevant to the given project (with an eye to future reuse in similar projects). 例如, Button 就只注意 Button 該有啥屬性, Button 該有哪些函數可以用? 先不管其它不相干的! 65 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-65 Abstraction Example (1/2) •Example from javax.swing.*; public abstract class AbstractButton Fields: protected ButtonModel model etc. The data model that determines the button’s state Methods: void addActionListener (ActionListener l); String getActionCommand( ); Apply to any button: String getText( ) “regular” button, a etc. checkbox, a toggle button, etc. Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 66 Slide 8-66 Abstraction Example (2/2) java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.AbstractButton Extends features of other abstract and concrete classes 67 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-67 Class vs. Object (1/2) • 討論用class製作 stack 之前先認識object與class – object 就是“東西”, 就是以前的“變數” – class 就是“類別”, 某種東西的型別(type) int m, n; /* int 是整數類別 */ /* m, n 都是變數 */ Student x, y; /* Student 是我們自訂類別 */ /* x, y 都是 object */ 68 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-68 Class vs. Object (2/2) • object is an instance of some class • 文法上, C++的class 就是以前的 struct class Student { public: /* …與寫 struct 同 */ }; struct Node { private: /* …與寫 class 同 */ }; // Java 已經取消 struct 69 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-69 Object Concept (1/3) • Why using class – 支援 OOP (物件導向Object Oriented Programming) – 又譯作 個體導向程式設計 – 考慮 Stack 堆疊 : 讓東西用起來更像東西 • ADT (Abstract Data Type)抽象資料型別 – 把 data 以及對 該些 data 有關的方法(method) 或稱函數(function, 函式))封裝(encapsulate)在一 個程式單元(例如class)方便使用 70 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-70 Object Concept (2/3) • Object-Oriented Analysis (OOA) – Goal: Understand the domain • Object-Oriented Design (OOD) – Goal: Design a solution, a model of the domain in which the desired activities occur • Object-Oriented Programming (OOP) – Goal: Implement the solution • Note: A Good Design is 2/3 Before You Hit the Keyboard 71 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-71 OO concept (3/3) #include "mystk.h" 以用物件方式使用堆疊 #include <iostream.h> int main( ) { Stack xo; /* xo is an object, it is a Stack */ xo.push(880); /* 要求 xo 把 880 push 進去 */ xo.push(770); xo.push(53); while(! xo.isempty( ) ) { cout << " " << xo.pop( ); /* 要求 xo 吐出頂端元素 */ /* .. .. .. */ } cout << endl; return 0; How to? 如何製作 Stack? } 請看稍後投影片 .. 72 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-72 Stack -- class example ( 1/2) mystk.h class Stack { // private: long data[99]; /* 直接寫 99 不是好習慣*/ int sptr; 標準程式庫的堆疊是stack public: 注意是小寫! 且其 pop( )是 void Stack( ) ; /* constructor */ void push( long ); 標準程式庫是empty long pop( ); bool isempty( ); }; /* class Stack */ // 注意右大括號後之分號 ; bool 要新版的 C++ 才有, 如果不能用就改用 int Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 73 Slide 8-73 Stack -- class example (2/2) mystk.cpp #include "mystk.h" #include <iostream.h> Initialization 工作 要寫在特殊函數 Stack::Stack( ) { sptr = -1; } /*Constructor*/ void Stack::push( long xx) { /*注意 Stack:: */ data[ ++sptr ] = xx; } long Stack::pop( ) {return data[sptr--];} bool Stack::isempty( ) { return sptr == -1;} // . . . bool 要新版的 C++ 才有 這是實作出 Stack, 前面 mystk.h只是宣告 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 74 Slide 8-74 Stack (使用) 如何執行? #include "mystk.h" gcc mymain.cpp mystk.cpp #include <iostream.h> ./a.out int main( ) { Stack xo, brandy; gcc –c mystk.cpp xo.push(880); gcc mymain.cpp mystk.o xo.push(770); xo.push(53); ./a.out while(! xo.isempty( ) ){ cout << " " << xo.pop( ); } cout << endl; /* new Line*/ 53 770 880 return 0; } 75 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-75 OO features Encapsulation Information Hiding The concept of abstraction is fundamental in programming 抽象化的概念以前就 有: 函數/副程式 Subprogram / function 增加: Inheritance Polymorphism process abstraction ADT Data abstraction Software Reuse 76 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-76 Encapsulation and information hiding • Encapsulation means that all data members (fields) of a class are declared private. Some methods may be private, too. • The class interacts with other classes (called the clients of this class) only through the class’s constructors and public methods. • Constructors and public methods of a class serve as the interface to class’s clients. • Ensures that structural changes remain local: – Usually, the structure of a class (as defined by its fields) changes more often than the class’s constructors and methods. – Encapsulation ensures that when fields change, no changes are needed in other classes (a principle known as “locality”). • Abstraction and encapsulation are helpful for the following: Team development, Reusable software, Easier program maintenance. 77 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-77 Abstract Data Type Binary_Tree (1/2) Node Structure in a Binary Tree data left child pointer right child pointer structure Binary_Tree(abbreviated BinTree) is objects: a finite set of nodes either empty or consisting of a root node, left Binary_Tree, and right Binary_Tree. functions: for all bt, bt1, bt2 BinTree, item element Bintree Create( )::= creates an empty binary tree Boolean IsEmpty(bt)::= if (bt==empty binary tree) return TRUE else return FALSE 78 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-78 Abstract Data Type Binary_Tree (2/2) BinTree MakeBT(bt1, item, bt2)::= return a binary tree whose left subtree is bt1, whose right subtree is bt2, and whose root node contains the data item Bintree Lchild(bt)::= if (IsEmpty(bt)) return error else return the left subtree of bt element Data(bt)::= if (IsEmpty(bt)) return error else return the data in the root node of bt Bintree Rchild(bt)::= if (IsEmpty(bt)) return error else return the right subtree of bt 79 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-79 Information Hiding Summary 3 access control clauses for C++ class members private: clause for hidden entities public: clause for interface entities protected: clause - for inheritance (extension) friend functions or classes - to provide access to private members in some unrelated program units or functions friend functions are not member functions of class – Defined outside of class scope if B a friend of A, A not necessarily a friend of B Java 不寫 access control modifier 表示 package available 80 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-80 Inheritance (繼承, 擴充) (1/3) class Animal{ long height; protected: double hehe; public: float weight; void jump( ) { /** … **/ } }; class Mankind : public Animal { long iq; public: void jump( ) { /** override **/ } void talk( ) { /** new **/ } }; In C++, ";" is required to terminate a class Copyright © 2009 Pearson Education, Inc. int main( ) { Animal x; Mankind y; x.jump( ); cout << sizeof(x)<<endl; cout << sizeof(y)<<endl; y.jump( ); y.talk( ); } 交大資工 蔡文能 計概 81 Slide 8-81 Inheritance (2/3) Inheritance lets us create new classes from existing classes Single inheritance: New class derived from one base class Multiple inheritance: New class derived from more than one base class (may cause problems) General syntax to define a derived class: Class className: memberAccessSpecifier baseClassName { // member list … } memberAccessSpecifier can be public, protected and private If no memberAccessSpecifier, it is a private inheritance 82 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-82 Inheritance (3/3) Protected Members of a Class The protected members of a class can be accessed by not only the other members inside the class, but also the members in its derived classes The protected members cannot be accessed outside the class If memberAccessSpecifier is public, all the members of the base class keep their access rights in the derived class If memberAccessSpecifier is protected, the public members of the base class become protected in the derived class, but the protected and private keep no change If memberAccessSpecifier is private, all the members of the base class become private in the derived class 若沒有繼承, 則寫 protected 與 private 完全相同 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 83 Slide 8-83 How can two classes be related? Inherits, Contains, TalksTo • Generalization-specialization or IsA – NamedBox IsA Box – Diagram: Triangle on the relationship line • Association or HasA – Box HasA Pen – Diagram: Just a relationship line – Aggregation is a part-whole relationship • Diagram: Diamond on the line • Dependency or TalksTo – Dependency is sort of temporary HasA • Diagram: Dashed line in UML (後面談到) – Example: A has a method that returns a B 84 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-84 Mankind inherits Animal (C++) Classes can be in same file class Animal { int height = 0; int weight = 0; public: void talk( ) { printf("Won");} }; public 繼承 class Mankind :public Animal { private: int iq = 120; public: void talk( ) { printf("Hello");} }; /* 分號不能省掉 */ In C++, ";" is required to terminate a class 85 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-85 manlib.h #ifndef __MANLIB__ #define __MANLIB__ class animal { // 建議大寫開頭: class Animal { int pv1; float pv2; protected: int pt1[5]; public: animal(int = 38); // default parameter float pb1; int pb2[9]; void talk(void); }; class Mankind:public animal { char * pv3; public: Mankind(char * ="NoName"); // Constructor with default 參數 ~Mankind( ); // Destructor int pb3[8]; void talk(void); }; #endif Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 86 Slide 8-86 manlib.cpp (1/2) // Implementation file for "animal" and "Mankind" #include <stdio.h> #include <iostream> //#include <iostream.h> // 舊的C++ 用 iostream.h using namespace std; // 舊的C++不能用 namespace #include "manlib.h" animal::animal(int x) { // constructor pv1=x; pv2=45.67; this->pb1=135.246; for (int i=0; i<9; i++) pb2[i]=i+1; //pb2={ 1,2,3,4,5,6,7 ,8,9}; cout<<" Animal shows up\n"; }; void animal::talk(void) { cout << " animal talk, pv1=" << dec <<pv1 <<"=0x" << hex << pv1 <<"\n"; cout << " \t pv2=" << pv2 <<"\n"; cout << " \t pb1=" << pb1 <<"\n"; cout << " \t pb2[6]=" << pb2[6] <<"\n"; }; 87 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-87 manlib.cpp (2/2) Mankind::Mankind(char * name){ pv3=name; cout << " Mankind "<< pv3 << " appears\n"; } Mankind::~Mankind(void){ cout << " %%% Mankind "<< this->pv3 << " is dying \n";} void Mankind::talk(void) { // cout << " Mankind talk, pv1=" << pv1 <<"\n"; // cout << " Mankind talk, pb2=" << pb2 <<"\n"; // cout << " Mankind talk, pb2=" << animal::pb2 <<"\n"; cout << " Mankind talk, pb2[0]=" << pb2[0] <<"\n"; cout << " Mankind talk, pv3=" << pv3 <<"\n"; cout << " Mankind talk, pb3[3]=" << pb3[3] <<"\n"; }; 88 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-88 Using Mankind 與 animal (mannew.cpp) #include <stdio.h> #include <iostream> // 注意 // 舊的C++不能用 // #include <iostream.h> #define call #include "manlib.h" using namespace std; animal aa1(123), aa2(456); Mankind * mm1, *mm2; void onlyasub(void) { Mankind nobody; cout << " Now in routine onlyasub\n"; } main( ) { aa1.talk(); cout << "Welcome to C++\n"; call onlyasub(); mm1= new Mankind("Chang-3"); mm2= new Mankind("Lee-4"); cout << "mm1->pb1= " << mm1->pb1 << endl; cout << " (Let mm1 talk)\n"; mm1->talk( ); delete mm2; cout << " (and then Let mm1 talk" << " by animal method)\n"; mm1->animal::talk( ); return(0); } 89 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-89 Using Mankind 與 animal (mannew.cpp) #include <stdio.h> #include <iostream> // #include <iostream.h> #define call #include "manlib.h" using namespace std; // with 新寫法 animal aa1(123), aa2(456); Mankind * mm1, *mm2; void onlyasub(void) { Mankind nobody; cout << " Now in routine onlyasub\n"; } main(){ aa1.talk(); cout << "Welcome to C++\n"; call onlyasub(); mm1= new Mankind("Chang-3"); mm2= new Mankind("Lee-4"); cout << "mm1->pb1=" << mm1->pb1 << "\n"; cout << " (Let mm1 talk)\n"; mm1->talk( ); delete mm2; cout << " (and then Let mm1 talk by animal method)\n"; mm1->animal::talk( ); return(0); Copyright } © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 90 Slide 8-90 Test class Mankind and animal g++ -c manlib.cpp g++ mannew.cpp manlib.o ./a.out Animal shows up Animal shows up animal talk, pv1=123=0x7b pv2=45.67 pb1=135.246 pb2[6]=7 Welcome to C++ Animal shows up Mankind NoName appears Now in routine onlyasub %%% Mankind NoName is dying Animal shows up Mankind Chang-3 appears Animal shows up Mankind Lee-4 appears mm1->pb1=135.246 注意比對 running result 與 程式碼! (Let mm1 talk) Mankind talk, pb2[0]=1 Mankind talk, pv3=Chang-3 Mankind talk, pb3[3]=0 %%% Mankind Lee-4 is dying (and then Let mm1 talk by animal method) animal talk, pv1=38=0x26 pv2=45.67 pb1=135.246 pb2[6]=7 91 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-91 問題與思考: inherit == extend class 豪華鬧鐘 : public 鬧鐘 { // …豪華鬧鐘 is_a 鬧鐘 }; class Stack : private Deque { // … }; class Stack { Deque x; // … }; class Stack : public Vector { // … }; class Stack { Vector x; // … }; 92 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-92 Mankind extends Animal (Java) Should be in different files public class Animal { private int height = 0; private int weight = 0; public void talk( ) { System.out.println(“Arhh");} } public class Mankind extends Animal { private int iq = 120; public void talk( ) { System.out.println("Hello");} } 不 要 管 文 法 Mankind is-a Animal One Java file can only have one public class Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 93 Slide 8-93 Upcasting and Polymorphism Upcasting: Taking an object reference and treating it as a reference to its base type is called upcasting, because of the way inheritance trees are drawn with the base class at the top. .•沒有 upcasting 就沒有所謂的Polymorphism(多型) •Base class 的指標(C++)可以指向 derived class 的 object •Base class 的參考(reference, in Java) 可以參考到derived class 的 object •Example: 牛肉麵, 豬肉麵, 羊肉麵 --- 都是麵 (upcasting) 麵 * p = new 牛肉麵( ); ( Java 則不可寫 * ) Polymorphism ensures that the appropriate method is called for an object of a specific type when the object is disguised as a more generic type Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 94 Slide 8-94 Polymorphism (多型) in C++ Suppose p is a pointer which points to an object class Circle and Line both inherit from Shape. All classes have their own draw( ) functions. Shape * p; /* the draw( ) in Shape is virtual or not ? */ . p = new Circle( ); P->draw( ); /* which draw( ) will be executed ? */ p = new Line( ); P->draw( ); /* which draw( ) will be executed ? */ If draw( ) is virtual, P->draw( );will run the correct draw( ) 95 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-95 Polymorphism (多型) in Java Suppose p is an Object of Shape which is actually a “reference” class Circle and Line both inherit from Shape. All classes have their own draw( ) functions. Shape p; // the draw( ) in Shape is virtual or not ? . p = new Circle( ); P.draw( ); // which draw( ) will be executed ? p = new Line( ); P.draw( ); // which draw( ) will be executed ? In Java, all functions are automically virtual, except final one 96 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-96 Polymorphism, C++ example (1/2) // polymo.cpp -- CopyWrong by [email protected] #include <iostream.h> class Shape{ public: virtual // 把這列去掉再 run 看看, 去掉就沒 polymorphism void draw( ) { cout << "drawing\n"; } }; class Line: public Shape{ public: void draw( ) { cout << "draw a line\n"; } }; class Circle: public Shape{ public: void draw( ) { cout << "here is a circle\n"; } }; 97 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-97 Polymorphism, C++ example (2/2) int main( ) { Circle * ppp; Shape * fig[9]; // base class的指標可指向衍生出的object // ppp = new Shape( ); // error! ppp = (Circle *)new Shape( ); /* cast */ ppp -> draw( ); ppp = (Circle *)new Line( ); ppp -> draw( ); ppp = new Circle( ); ppp -> draw( ); cout << "======" << endl; fig[0] = new Line( ); fig[1] = new Circle( ); fig[2] = new Circle( ); fig[3] = new Line( ); fig[4] = new Circle( ); for(int k=0; k<5; k++){ fig[k] -> draw( ); } } 98 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-98 Polymorphism:用 Base class 的pointer (C++) 或 是 reference (Java)去操作derived class 的物件 class Shape{ public: virtual void draw( ) = 0; // pure virtual function }; // Abstract class because it contains at least one pure virtual function class Circle: public Shape { // Circle is a Shape void draw( ) { } // must implement this }; Class Line: public Shape { void draw( ) { /*…*/ } }; // Line is a Shape Shape * p; p = new Shape( ); // Wrong ! 因為 Shape 為 ABC (Abstract Base Class) p = new Circle( ); // OK, good! P-> draw( ); // will run Circle::draw( ) P = new Line( ); p-> draw( ); // 用 Line 的 draw( ) Java的 Abstract class 必須用 abstract 開頭! 99 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-99 Why virtual function? • Virtual function to achieve Polymorphism – Dynamic binding : Shape * p; p-> draw( ); //被譯為執行 p 指過去的object所屬的 class之 draw( ) 函數. 該object有包括一指標會指到正 確的函數 (在 object 被 new 出之時才填入的, 例 p= new Circle( ); 時會填指標指向Circle( ) 的 draw() function ) • What if not virtual? Polymorphism (多型)! – Static binding 較有效率, 但可能錯 : 假設 draw( )不是 virtual Shape * p; p-> draw( ); //一定被譯為執行 Shape::draw( ); C++class 的 function 程式人員可決定是否 virtual Java 的 functions 永遠自動 virtual, except final functions Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 100 Slide 8-100 ABC (Abstract Base Class) • Abstract Base Class (抽象基底類別) – Base Class ? Derived class ? Super class ? – Abstract Class? • Class that contains pure virtual function (abstract function) • Virtual function? • Pure Virtual function? – virtual void haha( long para) = 0; – Abstract class 不可以用來生出 Object – 專為 polymorphism 而設的class, 提供其子孫有共同 一致的 interface 或說一致的 API C++ 的 pure virtual function 就是Java的 abstract function! 101 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-101 Polymorphism vs. Function name overloading • Function name overloading is implemented using a technique that change the function name to include types of all parameters. • Polymorphism is implemented using a technique called late (or dynamic) method binding: which exact method to call is determined at run time. Write a small C/C++ program and then have compiler to translate it into assembly source code: gcc -S file.c g++ -S file.cpp tcc -S file.c tcc -S file.cpp 102 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-102 C++ How to …overloading/polymorphism C++ 到底是用了什麼技術辦到 function name overloading ? 事實上 只是用了一個超級簡單的 idea: – C++只是把參數的型別納入函數名稱中而已, Compiler會偷換 function name, 參數的type也變成 function_name 的一部份: ( static binding) 例如: void swap(int&, int&); 會被譯為(可能!): __swap_F2RiRi 如何達成 polymorphism ? (C++ 要用到指標才有多型) 透過 virtual function dynamic binding p-> draw( ); 譯成去執行 p 指過去之物件內有個指標指 過去的函數表中draw的項目位置指過去的那個函數! (相關 指標在 new 出物件時填入) 若 draw( ) 不是 virtual, 則 p-> draw( ); 會採用 static binding 方式 翻譯, 即依據宣告看p是啥的指標直接譯出要執行哪個 function 103 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-103 問題與思考 (Why??) •現在用 class 製作軟體零件(元件), 雖可以 有許多個 long 的 Stack •若要一個 long 的 Stack 以及一個 double 的 Stack 呢? 甚至一個 Student 的 Stack 呢? • ? Copy 來改並換 class 名稱嗎? NO! Solution ==> using C++ template Class (樣版類別) (Generic type;汎用型別) 104 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-104 C++ Template (樣版); JDK1.5 以後有 Generic class type • Templates provide direct support for generic programming – The C++ template mechanism allows a type to be a parameter in the definition of a class or a function – definer specifies the container class in terms of that argument – users specify what the type of contained objects is • The template implementation is a mechanism that generates types when needed based on the user’s specification (compiler 幫忙copy去改 ) • Every major standard library abstraction is represented as a template (eg., C++ STL) 105 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-105 Generic data type -- Template class • 如何有多個可處理不同 data type的堆疊? template <class T> class Stack { T data[99]; int sptr; public : Stack( ); void push(T x); T top(void); void pop(void); template declaration, T is type argument T is uesd exactly like other type names Stack<int> xo; 不該改的不要改, 例 如 int sptr; 當然不改 int empty( ) ; // . . . Stack<double> brandy; Stack<Student> haha; }; Stack<T>::Stack( ) { sptr = -1; } /* … */ Copyright © 2009 Pearson Education, Inc. Class name is used exactly like others But you have to specify the type in < > 交大資工 蔡文能 計概 /* … */ 106 Slide 8-106 Template function (Generic function) • C++: template<class T, class T2> int myFun(T pa, T2 pb) { /* … */ } • Java: <T, T2> int myFun(T pa, T2 pb) { /* … */ } 107 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-107 Object Oriented Concepts • There are many OO tools for Software Engineering (軟體工程) • OOA (Language Independent) – CRC cards (Class-Responsibility-Collaborator) by Ward Cunningham and Beck • OOD – Class diagram, UML, Rational ROSE, … • OOP – Languages support OOP: C++, Java, Ada, … 108 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-108 OOA: CRC Cards • Step one: Write down all the objects that relate (Focus on the nouns because objects are nouns) • Step two: Write CRC cards and work through scenarios – Class-Responsibility-Collaborator Cards (Cunningham and Beck) – Just 3x5 cards •Although CRC is not part of UML, they add some very useful insights throughout a development. Copyright © 2009 Pearson Education, Inc. Data fields (attributes) 寫在背面 交大資工 蔡文能 計概 109 Slide 8-109 OOD: Object-Oriented Design, How? • Step one: Create a UML class diagram of your objects • Step two: Create a detailed description of the services to be performed – Peter Coad's "I am a Count. I know how to increment…" – Activity, sequence, or collaboration UML diagrams UML == “Unified Modeling Language” 110 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-110 OO Design is an Art • Object Oriented is a solution to Large software system • Designing a good OOP application is a daunting task. • It is largely an art: there are no precise rules for identifying classes, objects, and methods. • Many considerations determine which classes should be defined and their responsibilities. • A bad design can nullify all the potential OOP benefits. 111 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-111 Tips to find/determine classes • A few considerations that determine which classes are defined and their responsibilities: – – – – – – Manageable size Clear limited functionality Potential reuse Support for multiple objects The need to derive from a library class The need to make a listener or to implement a particular interface – The need to collect a few data elements in one entity 112 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-112 Façade Design Pattern • Façade: defines a clean, high-level interface to a subsystem. • Context: building easy-to-use and maintain subsystems • Problem: Each class in the subsystem provides part of the subsystem’s functionality, clients has to know the inside, changes to the subsystem may require changes to the clients. • Solution: Add an interface class (the façade class) that knows the structure of the subsystem and forwards requests… • Consequences: no or less dependency of client from structure of subsystem, ideal for layered subsystems Facade 113 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-113 MDA-Model Driven Architecture? • A New Way to Specify and Build Systems – 2001年由OMG制定的新開發架構 (http://www.omg.org) – 以UML Model(塑模)為基礎 – 支援完整開發週期: Analysis, Design, Implementation, Deployment, Maintenance, Evolution & Integration with later systems (改進與後續整合) – 內建協同運作性及跨平台性 – 降低開發初期成本及提高ROI (投資報酬) – 可套用至你所使用的任何環境: • Programming language Network • Operating System Middleware ROI : Return On Invest Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 114 Slide 8-114 Unified Modeling Language http://www.omg.org http://www.UML.org • There have been O-O gurus for many years • Three of them worked together to define UML (“Three amigos”: Booch, Rumbaugh, Jacobson) • Not so much a language, but more a process for designing software • Has now been approved as a standard by the Object Management Group (OMG) • Very powerful, many forms of notation – It's even provable! (with OCL) amigos = friends Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 (Object Constrain Language) 115 Slide 8-115 So, What is UML? 軟體工程師共通的語言 • UML is a Unified Modeling Language • UML is a set of notations, not a single methodology • Modeling is a way of thinking about the problems using models organized around the real world ideas. • Resulted from the convergence of notations from three leading Object-Oriented methods: • Booch method (by Grady Booch) • OMT (by James Rumbaugh) • OOSE (by Ivar Jacobson) • You can model 80% of most problems by using about 20% of the UML UML is a “blueprint” for building complex software 116 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-116 History of the UML( http://www.uml.org/ ) Public Feedback Approved 2004 UML 2.0 Minor revision 2003 UML 1.5 Minor revision 2001 UML 1.4 Minor revision 1999 UML 1.3 OMG Acceptance, Nov 1997 Final submission to OMG, Sept 1997 First submission to OMG, Jan 1997 UML 1.1 UML partners UML 1.0 Web - June 1996 UML 0.9 OOPSLA 95 Unified Method 0.8 Other methods OOSE Booch method 交大資工 蔡文能 計概 Copyright © 2009 Pearson Education, Inc. 117 OMT Slide 8-117 UML 常用的 Diagrams (目前共有12種) • Use case diagrams – Functional behavior of the system as seen by the user. • Class diagrams – Static structure of the system: Objects, Attributes, and Associations. • Activity diagrams – Dynamic behavior of a system, in particular the workflow, i.e. a flowchart. • Sequence diagrams – Dynamic behavior between actors and system objects. • Statechart diagrams – Dynamic behavior of an individual object as FSM (有限狀態機). UML is a modeling language that only specifies semantics and notation 118 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-118 UML 12 Diagrams • Structural: • Behavior : – Use Case – Sequence – Collaboration – State Chart – Activity – Class – Component – Deployment – Object • Model Management: – Packages (class diagram contains packages) – Subsystems (class diagram contains subsystems) – Models (class diagram contains models) 119 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-119 UML Core Conventions • Rectangles are classes or instances • Ovals are functions or use cases • Types are denoted with non-underlined names SimpleWatch Firefighter • Instances are denoted with an underlined names myWatch:SimpleWatch Joe:Firefighter • Diagrams are higraphs Higraphs are an extension to the familiar Directed Graph structure where nodes are connected by edges to other nodes. Nodes represent entities in some domain (in our case, classes, packages, methods, etc.). – Nodes are entities (e.g. classes, states) – Arcs are relationships among entities (e.g. sender/receiver) – Containment represents belonging (e.g. use cases in package) 120 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-120 Use Case Diagram examples Package SimpleWatch Actor A use case documents the interaction between the system user and the system. It is highly detailed in describing what is required but is free of most implementation details and constraints. ReadTime WatchUser Use case SetTime WatchRepairPerson ChangeBattery Use case diagrams represent the functionality of the system from user’s point of view. (強調 what, 但暫不管 how) 121 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-121 Class Diagram : a simple Watch Class Multiplicity Association SimpleWatch 1 2 PushButton state push() release() 1 1 1 1 2 LCDDisplay blinkIdx blinkSeconds() blinkMinutes() blinkHours() stopBlinking() referesh() Attributes Battery load() 1 Time now() Operations Class diagrams represent the structure of the domain or system 122 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-122 Sequence Diagram Object :WatchUser :SimpleWatch pressButton1( ) pressButton1() :LCDDisplay :Time blinkHours() blinkMinutes() pressButton2() incrementMinutes() refresh() pressButtons1And2() Activation commitNewTime() stopBlinking() Activation Message Sequence diagrams represent the behavior as interactions It shows sequence of events for a particular use case • A Sequence diagram shows the explicit sequence of messages suitable for modeling a real-time system, whereas a collaboration diagram (next slide) shows the relationships between objects. 123 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-123 Collaboration Diagram • A collaboration diagram and sequence diagram conveys similar information but expressed in different ways. • A collaboration shows the relationships among objects • Describes the set of interactions between classes or types Object diagram with numbered messages Sequence numbers of messages are nested by procedure call 124 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-124 State chart Diagrams for the watch Event Initial state button1&2Pressed Increment Hours button1Pressed Transition button1&2Pressed button2Pressed Blink Hours State Blink Minutes button2Pressed Increment Minutes button1Pressed button1&2Pressed Blink Seconds Stop Blinking Final state button2Pressed Increment Seconds FSM: Finite State Machine 125 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-125 Activity Diagrams • An activity diagram shows flow control within a system Handle Incident Document Incident Archive Incident • An activity diagram is a special case of a state chart diagram in which states are activities (“functions”) • Two types of states: – Action state: • Cannot be decomposed any further • Happens “instantaneously” with respect to the level of abstraction used in the model – Activity state: • Can be decomposed further • The activity is modeled by another activity diagram 描述Business process或use case的操作流程; 像流程圖 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 126 Slide 8-126 Classes in UML • Classes describe objects – Behaviour (member function signature / implementation) – Properties (attributes and associations) – Association, aggregation, dependency, and inheritance relationships – Multiplicity and navigation indicators – Role names • Objects described by classes collaborate – Class relations → object relations – Dependencies between classes 127 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-127 Visibility shown as + public private # protected UML Class Class name Data members (attributes) Instance methods Class method (static) Return types Arguments Data members, arguments and methods are specified by visibility name : type Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 128 Slide 8-128 Class Attributes Attributes are the instance data members and class data members Class data members (underlined) are shared between all instances (objects) of a given class Class name Attribute compartment Data types shown after ":" Visibility shown as + public private # protected visibility name : type 129 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-129 Class Operations (Interface) Operations are the class methods with their argument and return types Public (+) operations define the class interface Class methods (underlined) can only access to class data members, no need for a class instance (object) Operations compartment 130 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-130 Template Classes Type parameter(s) Operations compartment as usual, but may have type parameter instead of concrete type Generic classes depending on parametrised types 131 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-131 Class Inheritance Base class or super class Arrow shows direction of dependency (B inherits A) Derived class or subclass → → → Copyright © 2009 Pearson Education, Inc. B inherits A's interface, behaviour and data members B can extend A, i.e. add new data members or member functions B depends on A, A knows nothing about B 132 交大資工 蔡文能 計概 Slide 8-132 Multiple Inheritance (Java) The derived class inherits interface, behaviour and data members of all its base classes implements Extension and overriding works as before extends B implements the interface A and is also a "countable" class since it inherits class Countable class B extends Countable implements A { /*…*/ } Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 133 Slide 8-133 Class Friendship Java has NO friend Friends are granted access to private data members and member functions Friendship is given to other classes, never taken Friendship breaks data hiding, use carefully ! Friend is the only one who can touch your private! Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 134 Slide 8-134 Java has NO friend • Java does not have the friend keyword from C++. • However, there is a way to emulate that. Please see these: – http://macchiato.com/columns/Durable7.html – http://www.langer.camelot.de/Publications.htm • Friend function or member function? – If the first parameter is NOT an object of the current class, you have to write it as a friend function so that it can access the private members – If the first parameter is an object of the current class, then you can write it as a member function and/or as a friend function 135 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-135 Recommended Book: UML Distilled • UML Distilled by Martin Fowler is a great practical introduction to UML – Official UML book series published by AddisonWesley – Serious O-O designers DO use UML http://www.omg.org 136 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-136 UML Tools • Most complete tool: Rational Rose, http://www.rational.com • Lots of others : – Together by Object International, – Borland Together 2006 http://www.togethersoft.com – BOOST (Basic Object-Oriented Support Tool) by Noel Rappin, available on CD/CoWeb – Argo-UML, ObjectPlant, Posiden, etc. 137 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 Slide 8-137 Thank You! Data Abstraction 謝謝捧場 [email protected] 蔡文能 Copyright © 2009 Pearson Education, Inc. 交大資工 蔡文能 計概 138 Slide 8-138