Upload
laurel-wright
View
260
Download
1
Embed Size (px)
Citation preview
交通大學資訓工程學系 蔡文能
1
More about OOP
蔡文能[email protected]@cs.nctu.edu.tw
交通大學資訊工程學系2006/11/09
http://www.csie.nctu.edu.tw/~tsaiwn/java/
交通大學資訓工程學系 蔡文能
2
Agenda
• Other OO Languages
• OO tools– Other OO languages: Java, C#– CRC card– Façade Design Pattern– UML
http://www.csie.nctu.edu.tw/~tsaiwn/cpp
交通大學資訓工程學系 蔡文能
3
Other O-O Languages (1/2)
• C++ (Java = C++--++)In fact, Java is very similar to C++, except:
• All user-defined types are classes• All objects are allocated from the heap and accessed through
reference variables, including Arrays• Individual entities in classes have access control modifiers
(private or public), rather than clauses• All inheritances are public; all functions are virtual except
final• No operator overloading; No destructor; No pointer type• Java has a second scoping mechanism, package scope,
which can be used in place of friends– All entities in all classes in a package that do not have access
control modifiers are visible throughout the package
交通大學資訓工程學系 蔡文能
4
Other O-O Languages (2/2)
• C# ( 唸作 C-Sharp, by MicroSoft)– Based on C++ and Java– Adds two access modifiers, internal and protected internal– All class instances are heap dynamic (same as in Java)– Default constructors are available for all classes– Garbage collection is used for most heap objects, so destructors are rar
ely used– structs are lightweight classes that do not support inheritance– Common solution to need for access to data members: accessor metho
ds (getter and setter)– C# provides properties as a way of implementing getters and setters w
ithout requiring explicit method calls
交通大學資訓工程學系 蔡文能
5
• 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.
ADT --- Data Abstraction
交通大學資訓工程學系 蔡文能
6
OO featuresEncapsulationInformation Hiding The concept of abstraction is
fundamental in programming
Subprogram / function
process abstraction
ADT
Data abstractionSoftware Reuse
增加 :InheritancePolymorphism
抽象化的概念以前就有 : 函數 / 副程式
交通大學資訓工程學系 蔡文能
7
認真看 class• C 語言的 struct 目的是把相關資料 group 在一起• class ( 類別 ) 就是原來的 struct with some regulations• class is a user-defined data type, 自訂的 , 抽象的• 所以 class 是 Abstract Data Type (ADT)• ADT 就是把 data 以及對這些 data 有關的動作 (method, 就
是 function) 一起封藏 (Encapsulate) 在一個程式單元 (program unit) 之內 , 例如 C++ 用 class 來封藏
• Class 可用來設計軟體元件 (Software Component)• Class 內的 data member/method member 存取控制 :
– private, protected, public (C++ 與 Java 寫法不同 )
• Constructor? Destructor? Default Constructor? …• Java 沒有 Destructor, 但有 finalize 函數
交通大學資訓工程學系 蔡文能
8
Constructor 就是與 Class 同名的函數 Constructor 函數沒有 type, 不可以寫 return type Constructor 將在 object 被安排好記憶體後立即執行 , 所
以通常用來設定初值 (initial value) Student x; // 這樣會幫 x 安排一塊記憶體 , 並執行 x.Student( ); Student * p; // 這樣只有指標 , 沒有生出 Student, 不會執行
constructor, 要 p= new Student( ); 才會執行 constructor
Summary of Constructor in C++
Object 就是 Class 的一個 instance ( 案例 ); 就是 變數 啦 Constructor 可以不寫 , 此時等於有一個沒參數且不做事
的 Default constructor 只要寫了一個 Constructor, 則原先的 Default Constructo
r 就自動消失不能用了 Constructor 也可以寫很多個 , 自動依參數決定用哪個
此即 Function name overloading ( 函數名稱重複用 ) 的概念
交通大學資訓工程學系 蔡文能
9
Student x; // 這樣只會幫 x 安排一個參考 (reference, 其實就是 C++ 的指標 )必須再用 x = new Student( ); // 才會生出物件
Student * p; // 這樣在 Java 是錯的
Summary of Constructor in Java
交通大學資訓工程學系 蔡文能
10
OO tools
• There are many OO tools for Software Engineering ( 軟體工程 )
• OOA– CRC cards (Class-Responsibility-Collaborator)
• OOD– Class diagram, UML, Rational ROSE, …
• OOP– Languages support OOP: C++, Java, Ada, …
交通大學資訓工程學系 蔡文能
11
OOA: CRC Cards• Step two: Write CRC cards and work through scenarios
– Class-Responsibility-Collaborator Cards (Cunningham and Beck)– Just 3x5 cards
Data fields (attributes) 寫在背面
•Although CRC is not part of UML, they add some very useful insights throughout a development.
交通大學資訓工程學系 蔡文能
12
OOD: Object-Oriented Design
• 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
交通大學資訓工程學系 蔡文能
13
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
交通大學資訓工程學系 蔡文能
14
MDA-Model Driven Architecture?
• A New Way to Specify and Build Systems– 2001 年由 OMG 制定的新開發架構 (http://www.omg.o
rg)
– 以 UML Model( 塑模 ) 為基礎– 支援完整開發週期 : Analysis, Design, Implementation,
Deployment, Maintenance, Evolution & Integration with later systems ( 改進與後續整合 )
– 內建協同運作性及跨平台性– 降低開發初期成本及提高 ROI ( 投資報酬 )
– 可套用至你所使用的任何環境 :
• Programming language Network
• Operating System Middleware
交通大學資訓工程學系 蔡文能
15
Unified Modeling Language
• There have been O-O gurus for many years• Three of them worked together to define UML
(“Three amigos”: Booch, Rumbaugh, Jacobson)• 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)
http://www.UML.org
amigos = friends
http://www.omg.org
(Object Constrain Language)
交通大學資訓工程學系 蔡文能
16
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 m
odels organized around the real world ideas.• Resulted from the convergence of notations from three lea
ding 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
軟體工程師共通的語言
交通大學資訓工程學系 蔡文能
17
History of the UML( http://www.uml.org/ )
PublicFeedback
Web - June 1996 Web - June 1996 UML 0.9UML 0.9
Unified Method 0.8Unified Method 0.8OOPSLA 95OOPSLA 95
UML 1.0UML 1.0UML partnersUML partners
OMG Acceptance, Nov 1997Final submission to OMG, Sept 1997First submission to OMG, Jan 1997
OMG Acceptance, Nov 1997Final submission to OMG, Sept 1997First submission to OMG, Jan 1997
UML 1.1UML 1.1
UML 2.0UML 2.0Approved 2004Approved 2004
Minor revision 1999 Minor revision 1999 UML 1.3UML 1.3
UML 1.4UML 1.4Minor revision 2001Minor revision 2001
OOSEOther methods OMTBooch method
Minor revision 2003Minor revision 2003 UML 1.5UML 1.5
交通大學資訓工程學系 蔡文能
18
UML 常用的 Diagrams
• 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 ( 有限狀態機 ).
交通大學資訓工程學系 蔡文能
19
UML 12 Diagrams
• Behavior : – Use Case– Sequence– Collaboration– State Chart– Activity
• Structural:– Class– Component– Deployment– Object
• Model Management: – Packages (class diagram contains packages)– Subsystems (class diagram contains subsystems)– Models (class diagram contains models)
交通大學資訓工程學系 蔡文能
20
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– 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)
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.).
交通大學資訓工程學系 蔡文能
21
Use Case Diagram examples
WatchUserWatchRepairPerson
ReadTime
SetTime
ChangeBattery
Actor
Use case
PackageSimpleWatch
Use case diagrams represent the functionality of the systemfrom user’s point of view. ( 強調 what, 但暫不管 how)
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.
交通大學資訓工程學系 蔡文能
22
Class Diagram : a simple Watch
Batteryload()
1
2
Timenow()
PushButtonstatepush()release()
1
1
1
1
1
2
blinkIdxblinkSeconds()blinkMinutes()blinkHours()stopBlinking()referesh()
LCDDisplay
SimpleWatch
Class
Association
Operations
Class diagrams represent the structure of the domain or system
Attributes
Multiplicity
交通大學資訓工程學系 蔡文能
23
Sequence DiagramObject
MessageActivation
Sequence diagrams represent the behavior as interactionsIt shows sequence of events for a particular use case
blinkHours()blinkMinutes()
incrementMinutes()refresh()
commitNewTime()stopBlinking()
pressButton1()
pressButton2()
pressButtons1And2()
pressButton1()
:WatchUser :Time:LCDDisplay:SimpleWatch
Activation
Collaboration Diagram
Object diagram withnumbered messages
Sequence numbers of messages are nested by procedure call
交通大學資訓工程學系 蔡文能
24
button1&2Pressed
button1&2Pressed
button1Pressed
button2Pressed
button2Pressed
button2Pressed
button1Pressed
button1&2Pressed IncrementMinutes
IncrementHours
BlinkHours
BlinkSeconds
BlinkMinutes
IncrementSeconds
StopBlinking
State chart Diagrams for the watchStateInitial state
Final state
Transition
Event
FSM: Finite State Machine
交通大學資訓工程學系 蔡文能
25
Activity Diagrams• An activity diagram shows flow control within a system
• 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 的操作流程 ; 像流程圖
HandleIncident
DocumentIncident
ArchiveIncident
交通大學資訓工程學系 蔡文能
26
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
交通大學資訓工程學系 蔡文能
27
UML ClassClass name
Data members(attributes)
Instance methods
ArgumentsReturn typesClass method (static)
Data members, arguments and methods are specified byvisibility name : type
Visibility shown as+ public- private# protected
交通大學資訓工程學系 蔡文能
28
Class AttributesAttributes are the instance data membersand class data members
Class data members (underlined) are shared between all instances(objects) of a given class
Data types shown after ":"
Visibility shown as+ public- private# protected
Attributecompartment
visibility name : type
Class name
交通大學資訓工程學系 蔡文能
29
Class Operations (Interface)
Operations are the classmethods with their argumentand return types
Public (+) operations define theclass interface
Class methods (underlined) can only access to class datamembers, no need for a classinstance (object)
Operationscompartment
交通大學資訓工程學系 蔡文能
30
Template Classes
Generic classes depending on parametrised types
Type parameter(s)
Operations compartmentas usual, but may havetype parameter instead ofconcrete type
交通大學資訓工程學系 蔡文能
31
Class InheritanceBase class or super class
Derived class or subclass
Arrow shows directionof dependency (B inherits A)
→ B inherits A's interface, behaviour and data members
→ B can extend A, i.e. add newdata members or member functions
→ B depends on A,A knows nothing about B
交通大學資訓工程學系 蔡文能
32
Multiple Inheritance (Java)
The derived class inheritsinterface, behaviour anddata members of all itsbase classes
Extension and overridingworks as before
B implements the interface A andis also a "countable" class since itinherits class Countable
extends
implements
class B extends Countable implements A { /*…*/ }
交通大學資訓工程學系 蔡文能
33
A is associated with B
• A has a B
• A has a method that returns a B
• vice versa
• etc.
交通大學資訓工程學系 蔡文能
34
Class FriendshipFriends are granted access to private data members andmember functionsFriendship is given to other classes, never taken
Friendship breaks data hiding, use carefully !
Friend is the only one who can touch your private!
交通大學資訓工程學系 蔡文能
35
Recommended Book: UML Distilled
• Serious O-O designers DO use UML
• UML Distilled by Martin Fowler is a great practical introduction to UML
• Official UML book series published by Addison-Wesley
http://www.omg.org
交通大學資訓工程學系 蔡文能
36
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.
交通大學資訓工程學系 蔡文能
37
Thank You!Thank You!謝謝捧場
蔡文能
http://www.csie.nctu.edu.tw/~tsaiwn/java/