UML 클래스 다이어그램 표기법
(UML Class Diagram)
Objectives
• 자주 사용되는 UML 클래스도를 그릴 수 있다.
소개
• 클래스도 (Class Diagram)
– 클래스, 인터페이스 및 이들의 연관관계를 표현한 도식 – 정적 객체 모델링에 사용
• 이 장의 내용
– 모델링 관점을 떠나 클래스도 표기법 자체만을 다룸 – 참고자료로만 활용
• 중요한 것
– 도식을 그리는 기법보다 “객체지향 핵심원칙은 무엇인가”가 더 중요
1. UML적용하기: 클래스 다이어그램의 일반적 표기법
java . awt :: Font or java . awt . Font plain : Int = 0 { readOnly } bold : Int = 1 { readOnly } name : String
style : Int = 0 ...
getFont ( name : String ) : Font getName () : String
...
«interface»
Runnable run ()
SubclassFoo ...
run () ...
SuperclassFoo or
SuperClassFoo { abstract } - classOrStaticAttribute : Int
+ publicAttribute : String - privateAttribute
assumedPrivateAttribute isInitializedAttribute : Bool = true aCollection : VeggieBurger [ * ] attributeMayLegallyBeNull : String [ 0 .. 1 ] finalConstantAttribute : Int = 5 { readOnly } / derivedAttribute
+ classOrStaticMethod() + publicMethod() assumedPublicMethod() - privateMethod()
# protectedMethod()
~ packageVisibleMethod()
«constructor» SuperclassFoo (Long )
methodWithParms(param1:String, param2:Float) methodReturnsSomething(): VeggieBurger
methodThrowsException () { exception IOException } abstractMethod ()
abstractMethod 2 () { abstract } // alternate finalMethod () { leaf } // no override in subclass synchronizedMethod () { guarded }
3 common compartments
1 . classifier name 2 . attributes 3 . operations
interface implementation and
subclassing
Fruit ...
...
PurchaseOrder ...
...
1
association with dependency
officially in UML , the top format is used to distinguish the package name from the class name unofficially , the second alternative is common
order an interface
shown with a keyword
2. 정의: 설계 클래스도
• 설계 클래스도 (DCD: Design Class Diagram)
– 소프트웨어 객체의 정적 모델
Register ...
endSale () enterItem (...) makePayment (...)
Sale time
isComplete : Boolean / total
makeLineItem (...) Register
...
Sale time
isComplete : Boolean / total
Captures
1 1 1
Domain Model conceptual perspective
Design Model DCD ; software perspective
currentSale
3. 정의: 분류자
• 분류자 (classifier)의 정의
– 행위적이고 구조적인 특색을 표현하는 모델의 요소
– 예) 클래스, 인터페이스, 유스케이스, 액터 등을 지칭
4.속성의 표기 1: 속성 텍스트 및 연관관계 선
• 분류자의 속성(structural property)의 연관관계 표기
– currentSale:Sale 과 같은 속성 텍스트 (property text) 표기법
• 가시성 속성이름 : 타입 다중성 = 초기값{프로퍼티-문자열}
• 보통 가시성은 private 임.
– 연관관계 선 표기법 – 두 가지 혼합
Register ...
...
Sale ...
...
1 Register
currentSale : Sale ...
Sale ...
...
Register 가 Sale 객 체의 참조를 갖고 있 음ㅇ르 표시하기 위해 속성텍스트로 표현
Register 객체가 단 하나의 Sale 객체와 연관되었 음을 강조
Register 가 Sale객체 를 참조하고 있음을 시 각적으로 강조하고 있
음 currentSale
Register currentSale : Sale ...
Sale ...
...
1 중복적으로 연관관계를
나타내고 있음.
currentSale
4. 속성의 표기 2: 속성 텍스트 및 연관관계 선
the association name, common when drawing a domain model, is often excluded (though still legal) when using class diagrams for a software
perspective in a DCD
Register id: Int
...
Sale time: DateTime ...
1 currentSale Register
id : Int
Sale time : DateTime Captures-current-sale
1 1
UP Domain Model conceptual perspective
UP Design Model DCD
software perspective
• 도메인 모델의 연관 vs. DCD 모델의 연관관계 표시
• 지침
– 출발지로부터 목적지로의 화살표 – 화살표 끝점에 표기된 다중성
– 끝점에 표기된 역할 이름 (rolename) : 참조한 변수의 이름이 됨
4. 속성의 표기 3: 데이터타입
Register id: Int
...
Sale time: DateTime ...
applying the guideline 1 to show attributes as attribute text versus as association lines
Store address: Address phone: PhoneNumber ...
1 Register has THREE attributes:
1. id
2. currentSale 3. location
currentSale
location
• 데이터 타입 (Data Type)
– 중요하지 않은 클래스들
– 예) Boolean, Date, Number, Character, String, Time, Address, Color, Geometrics(Point, Rectangle), Phone Number, SSN, UPC, ZIP, 나열형 등
– 데이터 타입 객체들은 속성에 표현하고, 중요한 클래스에 대한 참 조 속성들은 연관으로 표기한다.
public class Register { private int id;
private Store location;
private Sale currentSale;
…
}
4. 속성의 표기 3: 연관관계의 끝점 표기법
• 다중성
• 역할명
• {ordered} {ordered, List} 같은 프로퍼티 문자열
notice that an association end can optionally also have a property string such as {ordered, List}
Sale time: DateTime ...
SalesLineItem ...
...
1..*
lineItems {ordered, List}
Sale time: DateTime
lineItems : SalesLineItem [1..*]
or
lineItems : SalesLineItem [1..*] {ordered}
...
SalesLineItem ...
...
Two ways to show a collection attribute
public class Sale {
private DateTime time;
private List<SalesLineItem> lineItems = new ArrayList<SalesLineItem>;
…
5. 노트: 메모, 주석, 제약사항, 메소드 몸체
• 노트 기호
– 어디에든 붙일 수 있음
– 설명하고자 하는 대상과 노트기호와는 점선으로 연결
• 노트의 사용
– 주석, 메모
– UML 제약사항 : 항상 {} 로 묶어서 나타낸다.
– 메소드 몸체 = UML 오퍼레이션의 구현을 표기
Register ...
endSale ()
enterItem ( id , qty ) makeNewSale ()
makePayment ( cashTendered )
«method»
// pseudo - code or a specific language is OK public void enterItem ( id , qty )
{
ProductDescription desc = catalog . getProductDescription ( id ) ; sale . makeLineItem ( desc , qty ) ;
}
6. 오퍼레이션과 메소드 1
• 연산
– 클래스 박스 안의 세 번째 구획 – 오퍼레이션의 시그너쳐만을 표기 – 시그너쳐 표기법
• 가시성 이름(매개변수목록} : 반환타입 {프로퍼티문자열}
– 지침
• 가시성은 기본적으로 public 으로 가정
• 프로퍼티문자열은 예외처리나 추상함수여부를 표현
• 예1) +getPlayer(name: String) : Player {exception IOException}
– Java 구현 public Player getPlayer(String name) throws IOException
• 예2) +getPlayer(name: String) : Player {abstract}
– C++ 구현 public: virtual Player getPlayer(String name)
• 메소드
– 연산을 구현한 것 – 표기법
• 인터랙션 다이어그램에서 메시지의 세부 내용을 기술
• 클래스도에서 UML 노트를 사용하여 기술
6. 오퍼레이션과 메소드 2
• DCD에서 연산에 대한 논의점
– Create 연산
• C++, Java 에서의 new 연산자 호출하는 것으로 구현됨
• 파라미터 타입에 맞는 생성자가 수행됨
– 속성에 접근하는 연산들 (setter, getter 연산들)
• DCD에는 가급적 나타내지 않음
• N 개의 속성이 있으면 2N개의 접근 연산이 필요
• 불필요하게 클래스도가 복잡해지므로 생략
7. UML 키워드 (Keyword)
• UML 키워드란?
– 모델 요소들을 범주로 나누기 위해 UML에서 미리 정해놓은 용어
– «» 를 사용
키워드 의미 사용 예
<<actor>> 액터이다. 분류자의 이름 위에
<<interface>> 인터페이스이다. 클래스 이름 위에 {abstract} 추상화된 요소이며 인스턴스
를 만들 수 없다.
클래스 이름 위 또는 연산 이 름 끝에 표기
{ordered} 순서 있는 객체의 집합 연관관계 끝점에 표기
8. 스테레오타입, 프로파일, 태그
• UML 프로파일
– 특정 도메인이나 플랫폼에 자주 사용되는 스테레오타입, 태그, 제약사항을 정의해 놓 은 집합
• 예) 프로젝트 관리용, 데이터 모델링 용 프로파일
• 스테레오 타입
– <<>>로 표기하는 것은 키워드와 같다.
– 도메인에서 자주 사용되는 용어로 미리 정해져 있거나 사용자가 정의 – UML 확장 메커니즘의 하나
• 태그
– 스테레오 타입의 {속성-값} 의 쌍을 태그라고 함
«stereotype»
Authorship author : String status : String UML extension
relationship to a basic UML metamodel term – Element
«authorship»
author = “craig”
status = “tested”
«metaclass»
Element ...
«authorship»
Square ...
스테레오타입의 사용
a tool will probably allow a popup to fill in the tag values , once an element has been stereotyped with «authorship»
스테레오타입의 정의
9. UML 프로퍼티 및 프로퍼티 문자열
• Property?
– “한 요소의 특징을 표시하는 명명된 값이다.”
– 예) 연산의 가시성 프로퍼티 : UML에서 미리 정해진 특징 – 문자열 표기법
• {name1=value,name2=value2}
– {abstract,visibility=public}
• {abstract} == {abstract=true}
10. 일반화, 추상 클래스, 추상 오퍼레이션
• 일반화
– Superclass 에서 서브클래스로 이어지는 실선 및 빈 화살촉으로 표 현
– 도메인 모델: 부분집합 – DCD : 상속을 의미
– 최종 클래스 및 최종 연산은 {leaf} 태그 사용 – 추상클래스는 {abstract} 또는 이탤릭체
Polygon
Rectangle
Polygon {abstract}
Rectangle
11. 의존관계
• 의존관계
– 어떤 도식에서도 사용가능
– 클래스도, 패키지도에서 주로 사용 – 의존관계의 정의
• 클라이언트 요소(클래스, 패키지, UC)가 서비스를 제공하는 공급자 요소의 정보 를 가지고 있어, 공급자 요소의 변화가 클라이언트에도 영향을 주는 관계로 정의 함.
• 의존관계 선은 클라이언트에서 공급자에게로 점선 화살표로 연결함.
• 의존관계는 결합도(coupling)의 한 형태로 인식할 수 있음
– 의존관계의 일반적 형태:클라이언트 A는 공급자 B에 의존한다.
• A가 공급자 B 타입의 속성을 가졌을 때
• A가 공급자 B로 메시지를 보낼 때 (연관)
• A의 함수가 공급자 타입의 매개변수를 받을 때
• 공급자 B가 A의 슈퍼클래스일 때 (상속/일반화 관계) – 특수한 형태의 의존관계는 해당 표기법을 사용
• 상속, 복합연관, 집합연관 – 지침
• 클래스도에서는 객체들간의 전역변수, 매개변수, 지역변수, 정적 메소드의 의존
관계를 표시할 때에 사용
의존관계의 예
SalesLineItem ...
...
ProductDescription ...
...
1..*
lineItems Sale
...
updatePriceFor( ProductDescription ) ...
the Sale has parameter visibility to a ProductDescription, and thus some kind of dependency
System ...
runFinalization() ...
Foo ...
doX() ...
the doX method invokes the runFinalization static method, and thus has a dependency on the System class
public class Sale {
public void updatePriceFor(ProductDescription desc) {
Money basePrice = desc.getPrice();
// … }
private SalesLineItem lineitems;
// … }
public class Foo { public void doX() {
System.runFinalization();
// … }
// … }
파라미터 의존 정적 메소드 호출
의존관계 레이블
• 의존관계의 특성을 표시하고 싶을 때
– 스테레오타입으로 표현
«call»
Window
a dependency on calling on operations of the operations of a Clock
Clock getTime () ...
«create»
A
a dependency that A objects create B objects B ...
12. 인터페이스
• UML에서의 인터페이스의 구현
– 인터페이스 실현 (interface realization) 관계 – 빈 촉을 가진 점선
• 인터페이스의 표기법
– 소켓, 원으로 표현
«interface»
Timer getTime ()
Clock 1 ...
getTime ()
... lollipop notation indicates Clock 3 implements and provides the Timer interface to clients Timer is a provided interface
Timer
Clock 3 ...
getTime () ...
Window 2
Window 3 dependency line notation
Window 2 has a dependency on the Timer interface when it collaborates with a Clock 2 object
socket line notation
Window 3 has a dependency on the Timer interface when it collaborates with a Clock 3 object
Window 1 Timer
socket line notation
Window 1 uses the Timer interface
it has a required interface
Clock 2 ...
getTime () ...
Clock 1
implements and provides the Timer interface
Timer
13. 집합(aggregation) 연관과 복합(composition) 연관
• 집합연관 (aggregation) – 약한 전체 부분관계
– 부분은 자체적으로 존재할 수 있고,없어질 수도 있다.
– 끝이 비어 있는 다이어몬드를 가진 선으로 표기
• 복합연관 (composition) – 강한 전체 부분관계
– 부분만으로는 존재할 수 없고 항상 전체와 동시에 존재 – 다음을 암시
• Square와 같은 부분 객체는 항상 Board 같은 복합 객체에만 속한다.
• 부분 객체는 항상 복합객체에 종속된다.
• 복합 객체가 부분 객체의 생성 및 삭제를 책임진다. 즉, 복합객체가 사라지면 부분 객체도
소멸된다.
– 끝이 채워진 다이어몬드를 가진 선으로 표기
Finger Hand 0..7
composition 1
1 40 1 1..*
composition means
-a part instance (Square) can only be part of one composite (Board) at a time
-the composite has sole responsibility for management of its parts, especially creation and deletion
14. 제약사항
• UML 제약사항 (constraints)
– UML 요소에 대한 제한 및 조건을 표시하기 위함 – 중괄호 {} 안에 제약조건 표시
• 표기법 3가지
Stack
size : Integer { size > = 0 } push ( element )
pop () : Object
three ways to show UML constraints
{ post condition : new size = old size + 1 }
{
post condition : new size = old size – 1 }
15. 한정적 연관관계
• 한정적 연관관계 (qualified association)
– 큰 집합에서 하나의 객체를 선택하여 관계를 한정할 때 쓰이며, 선 택된 객체를 한정자(qualifier)라고 한다.
– 대개의 경우 다중성이 감소함: 큰 집합에서 하나를 선택하기 때문
Product Catalog
Product Description
itemID Contains
Product Catalog
Product Description Contains
1..
*
multiplicity reduced to 1 (a)
(b)
qualifier 1
1 1
16. 연관관계 클래스
• 연관관계 클래스 (association class)
– 두 클래스 사이의 연관관계를 속성으로 가진 클래스를 지칭
– 예) Employment 는 Company 객체와 Person 객체를 이어주고, salary 및 startDate 를 추가 속성으로 가짐
• 구현
– 연관관계 클래스와 연관된 클래스들 간의 두 개의 연관으로 분리 후 구현
salary startDate
Employment Employs
Company
* *
Persona person may have employment with several companies
17. Singleton 클래스
• 디자인 패턴 중 Singleton 패턴에서 나오는 클래스
– 한 클래스의 인스턴스가 시스템을 통틀어 하나만 존재할 때
1 ServicesFactory
instance : ServicesFactory
accountingAdapter : IAccountingAdapter inventoryAdapter : IInventoryAdapter
taxCalculatorAdapter : ITaxCalculatorAdapter getInstance () : ServicesFactory
getAccountingAdapter () : IAccountingAdapter getInventoryAdapter () : IInventoryAdapter
getTaxCalculatorAdapter () : ITaxCalculatorAdapter ...
UML notation : in a class box , an
underlined attribute or method indicates a static ( class level ) member , rather than an instance member
UML notation : this ' 1 ' can optionally be used to indicate that only one instance will be created ( a singleton )
18. 템플릿 클래스 및 인터페이스
• 템클릿 클래스 (template class)
– C++, Java 의 템플릿 또는 매개변수화된 타입 등으로 불림
• 리스트 또는 맵 등의 collection 클래스들의 구현 방법 – 예) Square 요소를 갖는 ArrayList ArrayList<Square>
public class Board {
private List<Square> squares = new ArrayList<Square>
//…
}
«interface»
List clear () ...
parameterized or template K interfaces and classes K is a template parameter
anonymous class with template binding complete
Board
squares : List < K Square >
or
squares : List < Square >
...
ArrayList < T Square >
clear () ...
the attribute type may be expressed in official UML , with the template binding syntax requiring an arrow
or
in another language , such as Java
ArrayList elements : T [*]
...
clear () ...
T
for example , the elements attribute is an array of type T , parameterized and bound before actual use .
there is a chance the UML 2 “arrow” symbol will eventually be replaced with something else e . g . , ‘ = ’
19. 사용자 정의 구획
• 사용자 정의 구획
– 이름, 속성, 연산 등 UML에서 정의한 구획 외에 사용자가 정의한 구획을 클 래스 박스 안에 추가할 수 있음
– 예) 책임 구획, 예외처리 구획을 추가하여 사용
DataAccessObject id : Int
...
doX() ...
exceptions thrown DatabaseException IOException
responsibilities serialize and write objects read and deserialize objects ...
20. 액티브 클래스
• 액티브 객체
– 객체 자신의 쓰레드(thread)를 실행하고 제어
• 액티브 클래스
– 액티브 객체의 클래스
«interface»
Runnable run ()
Clock ...
run () ...
active class
21. 인터랙션 다이어그램 vs. 클래스 다이어그램
• 어떤 관계인가?
– 클래스 및 클래스의 메소드는 동적 모델링을 하는 창의적인 설계 과 정으로부터 정제되어 드러난다.
• 순서
– 동적 모델링 정적 모델링
– 병렬적 Agile 방법론에서는 상호 보완하면서 모델링
• 예) 10분 동적 모델링 후 10분 정적 모델링, 이를 반복
: Register : Sale
makePayment ( cashTendered ) makePayment ( cashTendered )
Register ...
Sale 1 ...
messages in interaction diagrams indicate operations
in the class diagrams classes
identified in the interaction diagrams are declared in the class diagrams