UML Class Diagram Tests
1. Shared-Target Inheritance
@startuml
class Animal {
+name: str
+speak()
}
class Dog {
+breed: str
+fetch(item: str)
}
class Cat {
+indoor: bool
+purr()
}
Dog --|> Animal
Cat --|> Animal
@enduml
2. Interface Realization (Dashed Arrows)
@startuml
interface Drawable {
+draw()
}
class Circle {
-radius: double
+draw()
}
class Rectangle {
-width: double
-height: double
+draw()
}
Circle ..|> Drawable
Rectangle ..|> Drawable
@enduml
3. All Relationship Types
@startuml
abstract class Shape {
-color: int
+{abstract} area(): double
+setColor(r: int, g: int, b: int)
}
class Rectangle {
-width: int
-length: int
+setWidth(width: int)
+setHeight(height: int)
}
class Color {
-r: int
-g: int
-b: int
}
class Canvas {
+render()
}
class Logger {
+log(msg: str)
}
Rectangle --|> Shape
Shape *-- Color
Shape o-- Canvas
Canvas ..> Logger : uses
@enduml
4. Multiplicities and Labels
@startuml
class University {
+name: str
}
class Professor {
+name: str
+department: str
}
class Student {
+name: str
+id: int
}
University "1" -- "*" Professor : employs
Professor "1" -- "*" Student : advises
@enduml
4b. Navigability Combinations (Association / Aggregation / Composition)
@startuml
layout portrait
class AssocUnspecified
class AssocNavigable
class AssocBidirectional
class AssocNonNavigable
class AssocNonNavigableBoth
class AssocTarget
class AggUnspecified
class AggNavigable
class AggBidirectional
class AggNonNavigable
class AggTarget
class CompUnspecified
class CompNavigable
class CompBidirectional
class CompNonNavigable
class CompTarget
AssocUnspecified -- AssocTarget : association (unspecified)
AssocNavigable --> AssocTarget : association (navigable)
AssocBidirectional <--> AssocTarget : association (bidirectional)
AssocNonNavigable --x AssocTarget : association (non-navigable)
AssocNonNavigableBoth x--x AssocTarget : association (non-navigable both ends)
AggUnspecified o-- AggTarget : aggregation (unspecified)
AggNavigable o--> AggTarget : aggregation (navigable)
AggBidirectional o<--> AggTarget : aggregation (bidirectional)
AggNonNavigable o--x AggTarget : aggregation (non-navigable)
CompUnspecified *-- CompTarget : composition (unspecified)
CompNavigable *--> CompTarget : composition (navigable)
CompBidirectional *<--> CompTarget : composition (bidirectional)
CompNonNavigable *--x CompTarget : composition (non-navigable)
@enduml
4c. Reverse-Direction Navigability (Explicit)
@startuml
layout portrait
class AssocL
class AssocR
class AssocL2
class AssocR2
class AggL
class AggR
class AggL2
class AggR2
class CompL
class CompR
class CompL2
class CompR2
AssocL <-- AssocR : association (navigable to left)
AssocL2 x-- AssocR2 : association (non-navigable to left)
AggL <--o AggR : aggregation (navigable to left)
AggL2 x--o AggR2 : aggregation (non-navigable to left)
CompL <--* CompR : composition (navigable to left)
CompL2 x--* CompR2 : composition (non-navigable to left)
@enduml
4d. Tolerant Alias Forms
@startuml
layout horizontal
class Alias1
class Alias2
class Alias3
Alias1 *<-->x Alias2 : alias for composition non-navigable
Alias2 ox--> Alias3 : alias for aggregation non-navigable
@enduml
5. Observer Design Pattern
@startuml
interface Observer {
+update(data: Object)
}
abstract class Subject {
-observers: List
+attach(o: Observer)
+detach(o: Observer)
+notify()
}
class ConcreteSubject {
-state: int
+getState(): int
+setState(s: int)
}
class ConcreteObserverA {
+update(data: Object)
}
class ConcreteObserverB {
+update(data: Object)
}
ConcreteSubject --|> Subject
Subject --> Observer : notifies
ConcreteObserverA ..|> Observer
ConcreteObserverB ..|> Observer
@enduml
6. Train System (from Lecture)
@startuml
class Train {
-lastStop: char
-nextStop: char
-velocity: double
-doorsOpen: boolean
+startTrain(velocity: double): void
+stopTrain(): void
+openDoors(): void
}
class Station {
+name: str
}
class Button {
+pressed: boolean
+press()
}
class RequestButton {
+press()
}
class EmergencyButton {
+press()
}
RequestButton --|> Button
EmergencyButton --|> Button
Station "1" -- "1" Button
Train "1" -- "2" Button
@enduml
7. Dependency
@startuml
class Train {
+addStop(stop: event): void
}
class ButtonPressedEvent {
+station: str
+timestamp: int
}
Train ..> ButtonPressedEvent
@enduml
8. Abstract Class with Stereotype
@startuml
class Singleton <<singleton>> {
-{static} instance: Singleton
-data: str
+{static} getInstance(): Singleton
+getData(): str
}
@enduml
9. Note with Constraint (Bottom)
@startuml
class BankAccount {
+owner: String
+balance: Number
+deposit(amount: Number)
+withdraw(amount: Number)
}
note bottom of BankAccount: {owner->notEmpty() and balance >= 0}
@enduml
10. Multi-line Note with Code and LaTeX
@startuml
class Order {
+id: int
+status: String
+total: double
}
class Customer {
+name: String
+email: String
}
Customer "1" -- "*" Order : places
note right of Order
Status transitions via `updateStatus()`:
CREATED -> PAID -> SHIPPED
Total must satisfy $total >= 0$
end note
@enduml
10b. Notes on Attributes and Operations
@startuml
class Account {
+owner: String
+balance: double
+deposit(amount: double)
+withdraw(amount: double)
}
note right of Account.owner: Must not be `null` or empty
note right of Account.withdraw: Throws `InsufficientFundsException`
@enduml
10b2. Observer Notes Avoid Relation Endpoints
@startuml
layout horizontal
interface Subject {
+attach(observer: Observer): void
+detach(observer: Observer): void
+notifyObservers(): void
}
interface Observer {
+update(): void
}
class ConcreteSubject {
-subjectState: String
+getState(): String
+setState(value: String): void
}
class ConcreteObserver {
-subject: ConcreteSubject
-observerState: String
+update(): void
}
ConcreteSubject ..|> Subject
ConcreteObserver ..|> Observer
Subject "1" -- "0..*" Observer : observers
ConcreteObserver --> ConcreteSubject : subject
note right of Subject.notifyObservers
for each o in observers {
o.update()
}
end note
note bottom of ConcreteSubject.getState: getState() returns subjectState
note bottom of ConcreteObserver.update
observerState =
subject.getState()
end note
@enduml
10c. Note with Python Syntax Highlighting
@startuml
class BankAccount {
+owner: String
+balance: float
+deposit(amount: float)
+withdraw(amount: float)
}
note right of BankAccount
```python
def withdraw(self, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
if amount > self.balance:
raise InsufficientFunds(self.balance)
self.balance -= amount
return self.balance
```
end note
@enduml
10d. Note with Java Syntax Highlighting
@startuml
class OrderService {
+placeOrder(order: Order): boolean
}
note right of OrderService
```java
public boolean placeOrder(Order order) {
if (order == null) {
throw new IllegalArgumentException("Order is null");
}
// Validate and persist
boolean saved = repository.save(order);
return saved;
}
```
end note
@enduml
10e. Note with JavaScript Syntax Highlighting
@startuml
class EventEmitter {
+on(event: String, callback: Function)
+emit(event: String, data: Object)
}
note right of EventEmitter
```javascript
async function emit(event, data) {
const listeners = this.listeners[event] || [];
for (const fn of listeners) {
await fn(data); // sequential
}
console.log("Done:", event);
}
```
end note
@enduml
10f. Note with C++ Syntax Highlighting
@startuml
class Matrix {
-rows: int
-cols: int
+transpose(): Matrix
}
note right of Matrix
```cpp
Matrix Matrix::transpose() const {
auto result = Matrix(cols, rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result(j, i) = this->at(i, j);
}
}
return result;
}
```
end note
@enduml
UML Sequence Diagram Tests
11. Basic Synchronous Call & Response
@startuml
participant client: Client
participant server: LibraryServer
client -> server: GET /book/id
activate server
server --> client: responseCode=200, book
deactivate server
@enduml
10. Alt Fragment
@startuml
participant client: Client
participant server: LibraryServer
client -> server: GET /book/id
activate server
alt [book found]
server --> client: responseCode=200, book
else [else]
server --> client: responseCode=404
end
deactivate server
@enduml
11. Multiple Participants (Login Flow)
@startuml
actor user: User
participant browser: WebBrowser
participant login: LoginController
participant auth: AuthService
participant db: UserDB
user -> browser: enter credentials
activate browser
browser -> login: POST /login
activate login
login -> auth: authenticate(user, pass)
activate auth
auth -> db: findUser(user)
activate db
db --> auth: userRecord
deactivate db
auth --> login: authResult
deactivate auth
login --> browser: 200 OK + token
deactivate login
browser --> user: show dashboard
deactivate browser
@enduml
12. Loop Fragment
@startuml
participant c: Client
participant s: Server
participant db: Database
c -> s: getItems(page)
activate s
loop [for each item in page]
s -> db: fetchItem(id)
activate db
db --> s: itemData
deactivate db
end
s --> c: itemList
deactivate s
@enduml
13. Opt Fragment (Optional)
@startuml
actor user: User
participant app: App
participant notif: NotificationService
user -> app: submitOrder()
activate app
opt [user has notifications enabled]
app -> notif: sendEmail(user, order)
activate notif
notif --> app: sent
deactivate notif
end
app --> user: orderConfirmation
deactivate app
@enduml
14. Train System Sequence (from Lecture)
@startuml
actor p: Passenger
participant btn: StationButton
participant sys: TrainSystem
participant train: Train
participant doors: Doors
p -> btn: press()
activate btn
btn -> sys: requestStop(stationA)
activate sys
sys -> train: stopTrain()
activate train
train --> sys: stopped
deactivate train
sys -> doors: openDoors()
activate doors
doors --> sys: doorsOpen
deactivate doors
deactivate sys
deactivate btn
p -> train: board
p -> train: pressRequestButton(stationB)
activate train
train -> sys: requestStop(stationB)
activate sys
sys -> doors: closeDoors()
activate doors
doors --> sys: doorsClosed
deactivate doors
sys -> train: startTrain(velocity)
activate train
deactivate train
deactivate sys
deactivate train
@enduml
15. Execution Specifications (Explicit Activation)
@startuml
participant client: Client
participant server: LibraryServer
participant db: Database
client -> server: GET /book/id
activate server
server -> db: SELECT * FROM books
activate db
db --> server: resultSet
deactivate db
server --> client: responseCode=200, book
deactivate server
@enduml
16. Nested Activations
@startuml
actor user: User
participant app: Application
participant auth: AuthService
participant db: UserDB
user -> app: login(credentials)
activate app
app -> auth: authenticate(user, pass)
activate auth
auth -> db: findUser(user)
activate db
db --> auth: userRecord
deactivate db
auth --> app: token
deactivate auth
app --> user: loginSuccess
deactivate app
@enduml
17. Self-Message
@startuml
participant client: Client
participant server: Server
client -> server: request()
activate server
server -> server: validate()
activate server
deactivate server
server -> server: process()
activate server
deactivate server
server --> client: response
deactivate server
@enduml
18. Lost and Found Messages
@startuml
participant client: Client
participant server: Server
o-> client: networkEvent
activate client
client -> server: request()
activate server
server ->o : timeout
server --> client: response
deactivate server
client ->o : logEntry
deactivate client
@enduml
19. Stacked Execution Specifications (Observer Pattern)
@startuml
participant Observer
participant Subject
Observer -> Subject: register(self)
activate Subject
Observer -> Subject: notify(someEvent)
activate Subject
Subject -> Observer: update()
activate Observer
Observer -> Subject: getData()
activate Subject
Subject --> Observer: data
deactivate Subject
deactivate Observer
deactivate Subject
deactivate Subject
@enduml
19b. Stacked Bars — Deep Nesting
@startuml
participant client: Client
participant server: Server
participant db: Database
client -> server: login()
activate server
server -> db: checkCredentials()
activate db
server -> db: loadProfile()
activate db
db --> server: profile
deactivate db
db --> server: valid
deactivate db
server --> client: session
deactivate server
@enduml
20. Nested Fragments (Loop containing Alt)
@startuml
participant c: Client
participant s: Server
participant db: Database
c -> s: fetchAll()
activate s
loop [for each record]
alt [found]
s -> db: query(id)
activate db
db --> s: record
deactivate db
s -> s: transform()
activate s
deactivate s
else [not found]
s -> db: query(id)
activate db
db --> s: null
deactivate db
s -> s: logMissing()
activate s
deactivate s
end
end
s --> c: results
deactivate s
@enduml
21. Destroy / Delete Message (Lifeline Termination)
@startuml
participant c: Client
participant s: Session
participant db: Database
c -> s: connect()
activate s
s -> db: open()
activate db
db --> s: connection
deactivate db
s --> c: sessionId
deactivate s
c -> s: query(sql)
activate s
s -> db: execute(sql)
activate db
db --> s: resultSet
deactivate db
s --> c: results
deactivate s
c -> s: disconnect()
activate s
s -> db: close()
activate db
deactivate db
destroy db
s --> c: bye
deactivate s
destroy s
@enduml
22. Break Fragment (Early Exit from Loop)
@startuml
participant c: Client
participant s: Server
participant cache: Cache
c -> s: search(query)
activate s
loop [for each page]
break [cache hit]
s -> cache: lookup(page)
activate cache
cache --> s: cachedResult
deactivate cache
s --> c: cachedResult
end
s -> cache: lookup(page)
activate cache
cache --> s: miss
deactivate cache
s -> s: computePage()
activate s
deactivate s
end
s --> c: result
deactivate s
@enduml
23. Par (Parallel) Fragment
@startuml
participant ui: UI
participant svc: OrderService
participant inv: Inventory
participant pay: PaymentGateway
participant notif: Notifications
ui -> svc: placeOrder()
activate svc
par [parallel processing]
svc -> inv: reserveItems()
activate inv
inv --> svc: reserved
deactivate inv
else [payment]
svc -> pay: chargeCard()
activate pay
pay --> svc: charged
deactivate pay
else [notification]
svc -> notif: sendConfirmation()
activate notif
notif --> svc: sent
deactivate notif
end
svc --> ui: orderComplete
deactivate svc
@enduml
24. Ref (Interaction Use) Fragment
@startuml
actor user: User
participant app: App
participant auth: AuthService
participant api: API
user -> app: login()
activate app
ref [Authentication Handshake]
app -> auth: authenticate(credentials)
activate auth
auth --> app: token
deactivate auth
end
app -> api: getData(token)
activate api
api --> app: data
deactivate api
app --> user: showDashboard
deactivate app
@enduml
25. Critical Fragment
@startuml
participant atm: ATM
participant bank: BankServer
participant acct: Account
atm -> bank: withdraw(amount)
activate bank
critical [atomic transaction]
bank -> acct: debit(amount)
activate acct
acct --> bank: success
deactivate acct
bank -> acct: updateBalance()
activate acct
acct --> bank: newBalance
deactivate acct
end
bank --> atm: dispenseCash
deactivate bank
@enduml
26. Multiple Else Clauses in Alt
@startuml
participant c: Client
participant s: Server
c -> s: request(type)
activate s
alt [type == GET]
s --> c: 200 OK + data
else [type == POST]
s -> s: validate()
activate s
deactivate s
s --> c: 201 Created
else [type == DELETE]
s -> s: authorize()
activate s
deactivate s
s --> c: 204 No Content
else [else]
s --> c: 405 Method Not Allowed
end
deactivate s
@enduml
27. Deeply Nested Fragments (3 Levels)
@startuml
participant c: Client
participant gw: Gateway
participant svc: Service
participant db: Database
c -> gw: request()
activate gw
opt [authenticated]
gw -> svc: process()
activate svc
loop [retry up to 3 times]
alt [success]
svc -> db: query()
activate db
db --> svc: data
deactivate db
else [timeout]
svc -> db: query()
activate db
deactivate db
svc -> svc: wait()
activate svc
deactivate svc
end
end
svc --> gw: result
deactivate svc
end
gw --> c: response
deactivate gw
@enduml
28. Neg (Forbidden/Invalid) Fragment
@startuml
actor user: User
participant sys: System
participant db: Database
user -> sys: deleteAccount()
activate sys
neg [must not happen during maintenance]
sys -> db: DROP TABLE users
activate db
db --> sys: error
deactivate db
end
sys --> user: maintenanceInProgress
deactivate sys
@enduml
29. Async Messages and Create/Destroy Lifecycle
@startuml
participant client: Client
participant pool: ThreadPool
participant worker: Worker
client ->> pool: submitTask()
activate pool
pool -> worker: create()
activate worker
deactivate worker
pool ->> worker: execute(task)
activate worker
worker ->> pool: taskComplete
deactivate worker
pool --> client: result
deactivate pool
destroy worker
@enduml
30. Sequence Diagram Notes
@startuml
participant c: Client
participant s: Server
participant db: Database
c -> s: authenticate()
activate s
note right of s: Validates JWT token
s -> db: findUser(token)
activate db
note left of db: Lookup by indexed token field
db --> s: userRecord
deactivate db
note over s
At this point the server has
verified the user identity and
can proceed with authorization.
end note
s --> c: authResult
deactivate s
@enduml
UML State Machine Diagram Tests
31. Exosuit State Machine (from SEBook)
@startuml
[*] --> Idle : powerOn()
Idle --> CombatMode : threatDetected [sysCheckOK] / deployUI()
CombatMode --> Idle : threatNeutralized / retractWeapons()
CombatMode --> EmergencyPower : powerLevel < 5% / rerouteToLifeSupport()
EmergencyPower --> [*] : manualOverride()
state Idle {
entry / initSensors()
exit / logStateChange()
}
@enduml
20. Order Lifecycle
@startuml
[*] --> Created : Order Placed
Created --> Paid : payment_received
Paid --> Shipped : ship_order
Shipped --> Delivered : delivery_confirmed
Delivered --> [*]
Created --> Cancelled : cancel_order [within 24hrs]
Paid --> Refunded : refund_requested / processRefund()
Cancelled --> [*]
Refunded --> [*]
@enduml
21. Simple Turnstile
@startuml
[*] --> Locked
Locked --> Unlocked : insertCoin
Unlocked --> Locked : push
@enduml
22. Vending Machine with Internal Actions
@startuml
[*] --> Idle
Idle --> AcceptingMoney : selectProduct
AcceptingMoney --> Dispensing : [sufficientFunds] / startDispense()
AcceptingMoney --> Idle : cancel / returnMoney()
Dispensing --> Idle : complete / resetMachine()
state AcceptingMoney {
entry / displayPrice()
do / countInsertedCoins()
}
state Dispensing {
entry / activateMotor()
exit / stopMotor()
}
@enduml
35. State Diagram with Note
@startuml
[*] --> Idle : init()
Idle --> Processing : startJob [queueNotEmpty]
Processing --> Done : complete
Done --> [*]
Processing --> Error : exception
Error --> Idle : retry
note right of Processing: Max 3 retries allowed
@enduml
UML Component Diagram Tests
36. Client-Server (from Lecture)
@startuml
component Client
component LibraryServer
Client --> LibraryServer : GET Book
Client --> LibraryServer : POST Book
@enduml
24. Three-Tier Architecture
@startuml
component WebUI
component AppServer
component Database
WebUI --> AppServer : HTTP Requests
AppServer --> Database : SQL Queries
AppServer ..> Logger : uses
@enduml
25. Microservices
@startuml
component APIGateway
component UserService
component OrderService
component PaymentService
component NotificationService
APIGateway --> UserService : /api/users
APIGateway --> OrderService : /api/orders
OrderService --> PaymentService : processPayment
OrderService ..> NotificationService : sendConfirmation
PaymentService ..> NotificationService : sendReceipt
@enduml
26. Frontend-Backend-Database (directional ports)
@startuml
component Frontend {
portout "httpOut" as f_out
}
component Backend {
portin "httpIn" as b_in
portout "dbOut" as b_dbout
portout "eventOut" as b_eventout
}
component Database {
portin "dbIn" as db_in
}
component EventBus {
portin "eventIn" as eb_in
}
f_out --> b_in : HTTP / JSON
b_dbout --> db_in : SQL
b_eventout --> eb_in : publish
@enduml
27. Microservice API Gateway (Port-to-Port)
@startuml
component Gateway {
portout "out1" as g_out1
portout "out2" as g_out2
}
component Auth {
portin "in" as a_in
portout "out1" as a_out1
portout "out2" as a_out2
}
component Users {
portin "/users" as u_p1
portin "/users" as u_p2
portin "/users/unsubscribe/{userId}" as u_p3
}
component Clubs {
portin "/clubs" as c_p1
portin "/clubs/event-reference/{eventId}" as c_p2
portin "/clubs/roles/{clubId}/{userId}" as c_p3
portout "out1" as c_out1
}
component Events {
portin "/events" as e_p1
portin "/events/template-data/{templateId}" as e_p2
portout "out1" as e_out1
portout "out2" as e_out2
}
component Notifications {
portin "/notifications/event-update" as n_p1
portout "out1" as n_out1
portout "out2" as n_out2
}
g_out1 --> c_p1 : POST
g_out2 --> u_p2 : POST
a_out1 --> u_p1 : GET
a_out2 --> c_p3 : GET
c_out1 --> e_p1 : GET
e_out1 --> c_p2 : GET
e_out2 --> n_p1 : POST
n_out1 --> e_p2 : GET
n_out2 --> u_p3 : POST
@enduml
27b. Component API Back-Edges with Shared Ports
@startuml
layout landscape
!theme plain
left to right direction
skinparam componentStyle uml2
skinparam nodesep 20
skinparam ranksep 150
' Hidden constraints keep the intended service sequence without rendering edges.
gateway -[hidden]r- auth
auth -[hidden]r- users
users -[hidden]r- clubs
clubs -[hidden]r- events
events -[hidden]r- notifications
component users {
portin "/users" as users_port
}
component clubs {
portin "/clubs" as clubs_port
}
component events {
portin "/events" as events_port
}
component notifications {
portin "/notifications" as notifications_port
}
notifications --> users_port : "patch /users/unsubscribe/{userId}"
notifications --> events_port : "get /events/template-data/{templateId}"
auth --> clubs_port : "get /clubs/roles/{clubId}/{userId}"
auth --> users_port : "post /users"
gateway --> users_port : "get /users"
gateway --> clubs_port : "get /clubs"
clubs --> events_port : "post /events"
events --> notifications_port : "post /notifications/event-update"
events --> clubs_port : "delete /clubs/event-reference/{eventId}"
@enduml
27c. Component Dashed Visual Style
@startuml
component Source dashed {
portout "events" as events dashed
}
component Worker {
portin "jobs" as jobs
portout "status" as status dashed
}
component Monitor
port "External Topic" as external_topic dashed
events --> jobs dashed : publish
status --> external_topic dashed : report
Worker --> Monitor dashed : observe
@enduml
27d. Standalone Labelled Ports
@startuml
component Publisher {
portout "out" as pub_out
}
component Subscriber {
portin "in" as sub_in
}
port "Kafka Topic" as topic dashed
pub_out --> topic dashed : produce
topic --> sub_in dashed : consume
@enduml
28. Joined Assembly Interfaces (Ball-and-Socket)
@startuml
component Order {
provide "OrderItems" as o_items
provide "CustomerInfo" as o_cust
}
component Warehouse {
require "OrderItems" as w_items
}
component CRM {
require "CustomerInfo" as crm_cust
}
o_items --> w_items
o_cust --> crm_cust
@enduml
29. Disjoined Interfaces (Standalone Lollipop and Socket)
@startuml
component WebApp {
provide "UserAPI" as wa_api
require "DataStore" as wa_ds
}
component Database {
provide "DataStore" as db_ds
}
component MobileApp {
require "UserAPI" as ma_api
}
wa_api ..> ma_api : REST
db_ds ..> wa_ds : JDBC
@enduml
40. Component Diagram with Note
@startuml
component Frontend
component API
component Database
Frontend --> API : REST
API --> Database : SQL
note right of API
All requests are authenticated
via JWT middleware before
reaching the handler.
end note
@enduml
UML Deployment Diagram Tests
41. Web Application Deployment
@startuml
node WebServer {
component Nginx
component AppServer
}
node DatabaseServer {
component PostgreSQL
}
node ClientDevice {
component WebBrowser
}
ClientDevice --> WebServer : HTTPS
WebServer --> DatabaseServer : TCP/IP
@enduml
27. Ticket System (from UML Reference)
@startuml
node TicketServer {
component TicketSeller
component CreditCardCharges
component TicketDB
}
node Kiosk {
component CustomerInterface
}
node SalesTerminal {
component ClerkInterface
}
Kiosk --> TicketServer : network
SalesTerminal --> TicketServer : network
@enduml
28. Microservices Deployment
@startuml
node LoadBalancer {
component Nginx
}
node AppNode1 {
component UserService
component OrderService
}
node AppNode2 {
component PaymentService
component NotificationService
}
node DataNode {
component MongoDB
component Redis
}
LoadBalancer --> AppNode1 : HTTP
LoadBalancer --> AppNode2 : HTTP
AppNode1 --> DataNode : TCP
AppNode2 --> DataNode : TCP
AppNode1 ..> AppNode2 : gRPC
@enduml
30. Web App Deployment — Horizontal Layout
@startuml
layout horizontal
node ClientDevice {
component WebBrowser
}
node WebServer {
component Nginx
component AppServer
}
node DatabaseServer {
component PostgreSQL
}
ClientDevice --> WebServer : HTTPS
WebServer --> DatabaseServer : TCP/IP
@enduml
31. Microservices — Horizontal Layout
@startuml
layout horizontal
node LoadBalancer {
component Nginx
}
node AppNode1 {
component UserService
component OrderService
}
node AppNode2 {
component PaymentService
component NotificationService
}
node DataNode {
component MongoDB
component Redis
}
LoadBalancer --> AppNode1 : HTTP
LoadBalancer --> AppNode2 : HTTP
AppNode1 --> DataNode : TCP
AppNode2 --> DataNode : TCP
AppNode1 ..> AppNode2 : gRPC
@enduml
29. Node Instance Notation (name:Type underlined, per UML spec Fig 9-3)
@startuml
node server:BankServer {
component Transactions
component AccountMgmt
}
node client:ATMKiosk {
component ATMSoftware
}
client:ATMKiosk --> server:BankServer : network
@enduml
50. Deployment Diagram with Note
@startuml
node LoadBalancer {
component HAProxy
}
node AppServer {
component NodeApp
}
node DBServer {
component PostgreSQL
}
LoadBalancer --> AppServer : HTTP
AppServer --> DBServer : TCP/5432
note right of DBServer: Encrypted at rest with AES-256
@enduml
Additional UML Regression Tests
51. Enumeration (Class Diagram)
@startuml
enum Color {
RED
GREEN
BLUE
}
enum Size { SMALL; MEDIUM; LARGE }
class Product {
-name: String
-color: Color
-size: Size
}
Product --> Color
Product --> Size
@enduml
52. Choice Pseudostate (State Machine)
@startuml
[*] --> Validating : submit
state Check <<choice>>
Validating --> Check : validate()
Check --> Approved : [valid]
Check --> Rejected : [invalid]
Approved --> [*]
Rejected --> [*]
@enduml
53. Actor Stick Figures (Sequence Diagram)
@startuml
actor user: User
participant app: Application
participant db: Database
user -> app: login(credentials)
activate app
app -> db: findUser(name)
activate db
db --> app: userRecord
deactivate db
app --> user: welcome screen
deactivate app
@enduml
54. Create Message (Sequence Diagram)
@startuml
participant client: Client
participant server: Server
client -> server: request()
activate server
create Handler
server --> Handler: <<create>>
activate Handler
Handler --> server: result
deactivate Handler
destroy Handler
server --> client: response
deactivate server
@enduml
55. Composite State (State Machine)
@startuml
[*] --> Active
state Active {
[*] --> Running
Running --> Paused : pause()
Paused --> Running : resume()
}
Active --> Idle : deactivate()
Idle --> Active : activate()
Idle --> [*] : shutdown()
@enduml
UML Use Case Diagram Tests
56. Login System (Use Case)
@startuml
actor User
actor Admin
usecase "Log In" as UC1
usecase "Register Account" as UC2
usecase "Reset Password" as UC3
usecase "Manage Users" as UC4
usecase "Confirm Email" as UC5
rectangle "Auth System" {
UC1
UC2
UC3
UC4
UC5
}
User -- UC1
User -- UC2
User -- UC3
User -- UC5
Admin -- UC1
Admin -- UC4
UC3 ..> UC1 : <<extend>>
UC2 ..> UC5 : <<include>>
@enduml
57. Online Store (Use Case)
@startuml
actor Customer
actor "Payment Gateway" as PaymentGateway
rectangle "Online Store" {
usecase "Browse Products" as UC1
usecase "Add to Cart" as UC2
usecase "Checkout" as UC3
usecase "Pay for Order" as UC4
}
Customer -- UC1
Customer -- UC2
Customer -- UC3
UC3 ..> UC4 : <<include>>
UC4 -- PaymentGateway
@enduml
Actor Inheritance — LMS with User Hierarchy
@startuml
actor User
actor Student
actor Instructor
usecase "Login" as UC1
usecase "View Course" as UC2
usecase "Submit Assignment" as UC3
usecase "Grade Submission" as UC4
rectangle "LMS" {
UC1
UC2
UC3
UC4
}
User -- UC1
User -- UC2
Student --|> User
Instructor --|> User
Student -- UC3
Instructor -- UC4
@enduml
Actor Inheritance — Hospital System
@startuml
actor "Medical Staff" as Staff
actor Doctor
actor Nurse
actor Patient
usecase "View Patient Records" as UC1
usecase "Prescribe Medication" as UC2
usecase "Administer Treatment" as UC3
usecase "Schedule Appointment" as UC4
usecase "Authenticate" as UC5
rectangle "Hospital System" {
UC1
UC2
UC3
UC4
UC5
}
Staff -- UC1
Doctor --|> Staff
Nurse --|> Staff
Doctor -- UC2
Nurse -- UC3
Patient -- UC4
UC1 ..> UC5 : <<include>>
@enduml
UML Activity Diagram Tests
58. Order Processing (Activity Diagram)
@startuml
(*) --> "Receive Order"
"Receive Order" --> "Validate Payment"
if "Payment Valid?" then
--> [yes] "Process Order"
else
--> [no] "Reject Order"
endif
"Process Order" --> "Ship Order"
"Ship Order" --> (*)
"Reject Order" --> (*)
@enduml
59. Login Flow (Activity Diagram)
@startuml
(*) --> "Enter Credentials"
"Enter Credentials" --> "Authenticate"
if "Valid?" then
--> [yes] "Load Dashboard"
"Load Dashboard" --> (*)
else
--> [no] "Show Error"
"Show Error" --> "Enter Credentials"
endif
@enduml
60. Swimlanes (Activity Diagram)
@startuml
|Customer|
(*) --> "Place Order"
|Warehouse|
"Place Order" --> "Pick Items"
"Pick Items" --> "Pack"
|Shipping|
"Pack" --> "Ship"
|Customer|
"Ship" --> "Receive"
"Receive" --> (*)
@enduml
61. Composition Crossing Test (Composite Pattern)
@startuml
layout landscape
abstract class Component {
+ operation(): void
+ add(child: Component): void
+ remove(child: Component): void
}
class Leaf {
+ operation(): void
}
class Composite {
- children: List<Component>
+ operation(): void
+ add(child: Component): void
+ remove(child: Component): void
}
class Client
Leaf --|> Component
Composite --|> Component
Composite "1" *--> "0..*" Component
Client --> Component : treats uniformly >
@enduml
61b. Association Label Direction Cues
@startuml
layout landscape
class Source
class Target
class Observer
Source -- Target : reads >
Observer -- Source : < publishes
@enduml
61c. Label Direction Cues Across Diagram Types
@startuml
participant Client
participant Server
Client -> Server : request <
@enduml
@startuml
state Ready
state Running
Ready --> Running : start >
@enduml
@startuml
component Client
component Gateway
Client --> Gateway : call <
@enduml
@startuml
node Browser
node Server
Browser --> Server : deploy >
@enduml
@startuml
actor User
usecase "Login"
User -- Login : starts <
@enduml
@startuml
(*) --> [go >] "Run"
"Run" --> (*)
@enduml
@startuml
box "A" as A
box "B" as B
A --> B : flows <
@enduml
62. Composition Behind Class Test (Order System)
@startuml
interface Billable {
+ processPayment(): bool
}
class Customer {
- id: int
- name: String
+ placeOrder(): void
}
class VIP
class Guest
class Order {
- date: Date
- status: String
+ calcTotal(): float
}
class LineItem {
- quantity: int
}
class Product {
- price: float
- name: String
}
VIP --|> Customer
Guest --|> Customer
Order ..|> Billable
Customer "1" -- "0..*" Order
Order *-- "1..*" LineItem
LineItem "0..*" -- "1" Product
@enduml
63. Composition Detour Test (Shape/Color)
@startuml
abstract class Shape {
- color: int
+ {abstract} area(): double
+ setColor(r: int, g: int, b: int)
}
class Color {
- r: int
- g: int
- b: int
}
class Canvas {
+ render()
}
class Logger {
+ log(msg: str)
}
class Rectangle {
- width: int
- length: int
+ setWidth(width: int)
+ setHeight(height: int)
}
Shape *-- Color
Rectangle --|> Shape
Canvas ..> Logger : uses
@enduml
64. Component Port Crossing Test
component Notifications {
portout "out1" as n_out1
portout "out2" as n_out2
portin "/notifications/event-update" as n_evup
}
component Templates {
portin "ts/template-data/{templateId}" as t_templ
portout "out2" as t_out2
}
n_out1 --> t_templ : GET
t_out2 --> n_evup : POST
65. Component Port Non-Crossing Test
component Backend {
portin "httpIn" as b_in
portout "dbOut" as b_db
portout "eventOut" as b_ev
}
component Database {
portin "dbIn" as d_in
}
component EventBus {
portin "eventIn" as e_in
}
b_db --> d_in : SQL
b_ev --> e_in : publish
66. Composition Behind Class (Circle/Drawing)
@startuml
interface Serializable {
+ serialize(): string
+ deserialize(data: string)
}
abstract class Shape {
# color: string
+ {abstract} area(): number
}
class Circle {
- radius: number
+ constructor(radius: number)
+ area(): number
+ serialize(): string
+ deserialize(data: string)
}
class Drawing
Circle ..|> Serializable
Circle --|> Shape
Circle *-- Drawing
@enduml
67. Aggregation/Composition Vertical (UserService)
@startuml
class UserService {
+ constructor(repo: UserRepository)
+ getUser(id: string): string[]
}
class UserRepository {
+ constructor(db: Database)
+ findById(id: string): string[]
}
class Database {
+ query(sql: string): string[]
}
class Cache {
+ get(key: string): string | null
+ set(key: string, value: string)
}
UserService o-- UserRepository
UserRepository o-- Database
UserRepository *-- Cache
@enduml
68. Aggregation Detour (Priority/Task)
@startuml
enum Priority {
+ Low
+ Medium
+ High
+ Critical
}
interface Identifiable {
+ getId(): string
}
interface Assignable {
+ assignTo(user: string)
}
class Task {
- id: string
- assignee: string
+ constructor(id: string, priority: Priority)
+ getId(): string
+ assignTo(user: string)
}
class Epic {
- subtasks: Task[]
+ addSubtask(task: Task)
}
Task ..|> Identifiable
Task ..|> Assignable
Epic --|> Task
Task o-- Priority
@enduml
69. Element Colors — Class Diagram
@startuml
class Plain
class Highlighted #lightblue
class Warning #FFEB3B
class Error #FF9999
class Success #99FF99
class Service <> #lightcoral
Plain --> Highlighted
Highlighted --> Warning
Warning --> Error
Error --> Success
Service --> Plain
@enduml
70. Element Colors — State Machine
@startuml
[*] --> Idle
Idle #lightblue --> Processing #FFEB3B : start
Processing --> Done #99FF99 : complete
Processing --> Failed #FF9999 : error
Failed --> Idle : reset
Done --> [*]
@enduml
71. Element Colors — Sequence Diagram
@startuml
participant Client #lightblue
participant Gateway #FFEB3B
participant Service #lightgreen
participant Database #lightcoral
Client -> Gateway : request
activate Gateway
Gateway -> Service : forward
activate Service
Service -> Database : query
activate Database
Database --> Service : result
deactivate Database
Service --> Gateway : response
deactivate Service
Gateway --> Client : reply
deactivate Gateway
@enduml
72. Element Colors — Component Diagram
@startuml
[Frontend] #lightblue
[API Gateway] #FFEB3B
[Auth Service] #lightgreen
[Data Service] #lightcoral
[Database] #pink
[Frontend] --> [API Gateway]
[API Gateway] --> [Auth Service]
[API Gateway] --> [Data Service]
[Data Service] --> [Database]
@enduml
73. Texture Overlays — Class Diagram
@startuml
class Plain
class Colour #lightblue
class Hatched #lightblue hatched
class Crosshatch #FFEB3B crosshatch
class Dotted dotted
class Grid #99FF99 grid
class Striped #pink striped
Plain --> Colour
Colour --> Hatched
Hatched --> Crosshatch
Crosshatch --> Dotted
Dotted --> Grid
Grid --> Striped
@enduml
74. Texture Overlays — State Machine
@startuml
[*] --> Draft
Draft dotted --> Review #FFEB3B hatched : submit
Review --> Approved #99FF99 grid : approve
Review --> Rejected #FF9999 crosshatch : reject
Rejected --> Draft striped : revise
Approved --> [*]
@enduml
75. Texture Overlays — Component Diagram
@startuml
[Legacy Module] #lightcoral hatched
[Deprecated API] dotted
[Active Service] #lightblue grid
[New Module] #99FF99
[Legacy Module] --> [Active Service]
[Deprecated API] --> [Active Service]
[Active Service] --> [New Module]
@enduml
76. Colors and Textures — Use Case Diagram
@startuml
actor User #lightblue
actor Admin #lightcoral
usecase "Login" as UC1 #lightgreen
usecase "View Dashboard" as UC2 #FFEB3B hatched
usecase "Manage Users" as UC3 #pink crosshatch
usecase "Generate Report" as UC4 dotted
User --> UC1
User --> UC2
Admin --> UC1
Admin --> UC3
Admin --> UC4
@enduml
77. Colors and Textures — Deployment Diagram
@startuml
node "Production" #lightgreen {
node WebServer #lightblue striped
node AppServer #FFEB3B grid
}
node "Staging" #FFEB3B hatched {
node StagingServer dotted
}
node "Database Cluster" #lightcoral crosshatch {
node Primary #99FF99
node Replica dotted
}
WebServer --> AppServer
AppServer --> Primary
Primary --> Replica
@enduml
78. Colors and Textures — Git Graph
@startuml
branch main:
A "Initial commit"
B "Add auth module"
C "Fix login bug" #FF9999
D "Release v1.0" #99FF99 hatched
branch feature from B:
α "Start OAuth" #lightblue
β "Implement flow" #lightblue dotted
γ "Tests pass" #FFEB3B crosshatch
branch hotfix from C:
h1 "Patch CVE" #FF9999 striped
head main
@enduml
79. Colors and Textures — Folder Tree
@startuml
project-root/
src/ #lightblue
components/ #lightblue hatched
Button.tsx #99FF99
Modal.tsx #99FF99 dotted
utils/
auth.ts #FFEB3B
helpers.ts
deprecated/ #FF9999 crosshatch
oldApi.ts #FF9999 striped
legacyAuth.ts #FF9999 striped
tests/ #lightcoral grid
Button.test.tsx
auth.test.ts
README.md
package.json #FFEB3B
@enduml
Venn Diagram Tests
80. Two-Set Venn (Default Palette)
@startuml
title Programming Languages
set Compiled
set "Memory Safe"
Compiled : C, C++
"Memory Safe" : Python, Ruby, JavaScript
Compiled & "Memory Safe" : Rust, Go, Swift
outside : Assembly
@enduml
81. Three-Set Venn (Classic Three-Circle)
@startuml
title Web Technologies
set Frontend
set Backend
set Database
Frontend : React, Vue
Backend : Django, Rails
Database : PostgreSQL, Redis
Frontend & Backend : Next.js, SvelteKit
Backend & Database : Prisma, SQLAlchemy
Frontend & Database : PouchDB
Frontend & Backend & Database : Firebase, Supabase
outside : Docker
@enduml
82. Four-Set Venn (All 16 Regions)
@startuml
title Developer Skills
set Frontend
set Backend
set DevOps
set Design
Frontend : React, CSS
Backend : APIs, SQL
DevOps : Docker, K8s
Design : Figma, UX
Frontend & Design : UI libs
Backend & DevOps : SRE
Frontend & Backend : Full-stack
DevOps & Design : Design ops
Frontend & Backend & DevOps : Platform eng
Frontend & Backend & Design : Product eng
Frontend & DevOps & Design : Frontend infra
Backend & DevOps & Design : Backend infra
Frontend & Backend & DevOps & Design : Unicorn
@enduml
83. Five-Set Venn (Grünbaum Ellipses)
@startuml
title Meals
set Breakfast
set Lunch
set Dinner
set Vegetarian
set Quick
Breakfast : Pancakes
Lunch : Club sandwich
Dinner : Steak
Vegetarian : Tofu
Quick : Toast
Breakfast & Quick : Cereal
Lunch & Vegetarian : Salad
Dinner & Vegetarian : Risotto
Breakfast & Vegetarian & Quick : Yogurt
Lunch & Dinner & Vegetarian : Veggie bowl
Breakfast & Lunch & Dinner & Vegetarian & Quick : Smoothie
@enduml
84. Custom Colors — Contrast Detection
@startuml
title Biomes
set Ocean #0077be
set Forest #228b22
set Desert #edc9af
Ocean : whale, kelp
Forest : oak, deer
Desert : cactus, scorpion
Ocean & Forest : mangrove
Forest & Desert : savanna scrub
Ocean & Desert : coastal dunes
Ocean & Forest & Desert : biosphere
@enduml
85. Custom Colors — CSS Named Colors (Light Fills)
@startuml
title Pastel Palette — Text Should Be Dark
set Alpha lightyellow
set Beta lightpink
set Gamma lightblue
Alpha : item1, item2
Beta : item3
Gamma : item4
Alpha & Beta : shared ab
Alpha & Gamma : shared ag
Beta & Gamma : shared bg
Alpha & Beta & Gamma : all three
@enduml
86. Venn with Notes on Intersections
@startuml
title Developer Skills
set Frontend
set Backend
set DevOps
Frontend : React
Backend : Django
DevOps : Docker
Frontend & Backend : Next.js
Backend & DevOps : Platform
Frontend & Backend & DevOps : SRE
note left of Frontend : Pure UI\nwork
note right of Frontend & Backend : Popular full-stack\nframeworks
note top of Frontend & Backend & DevOps : Rare but valuable
note bottom of DevOps
Infrastructure
specialists
end note
@enduml
87. Venn with Stacked Notes and Outside-Targeted Note
@startuml
title Notes Stacking
set A
set B
set C
A : item1
B : item2
C : item3
A & B : shared
outside : leftover
note right of A : Alpha stuff
note right of B : Beta stuff
note right of A & B : Combined A+B
note left of outside : dropped during\ntriage
@enduml
88. Venn with Quoted Set Names (Spaces)
@startuml
title Programming Languages
set Compiled
set "Memory Safe"
Compiled : C, C++
"Memory Safe" : Python, Ruby, JavaScript
Compiled & "Memory Safe" : Rust, Go, Swift
outside : Assembly
@enduml
ER Diagram Tests (Chen Notation)
89. Basic ER — Library System
@startuml
title Library System
entity Student {
# student_id
name
email
/ age
* phones
}
entity Book {
# isbn
title
* authors
}
relationship Borrows {
date_out
date_due
}
Student "N" -- Borrows
Book "M" -- Borrows
@enduml
90. Weak Entity with Identifying Relationship
@startuml
title Employee Dependents
entity Employee {
# emp_id
name
salary
}
weak entity Dependent {
~ dep_name
dob
relationship_type
}
identifying relationship Has
Employee "1" == Has
Dependent "N" == Has
@enduml
91. Ternary Relationship
@startuml
title University Enrolment
entity Student {
# sid
name
}
entity Course {
# cid
title
}
entity Semester {
# term
}
relationship Enrolls {
grade
}
Student "N" -- Enrolls
Course "M" -- Enrolls
Semester "1" -- Enrolls
@enduml
92. Multiple Relationships Between Entities
@startuml
title Hospital
entity Doctor {
# doc_id
name
specialty
}
entity Patient {
# pat_id
name
/ age
}
relationship Treats {
visit_date
}
relationship PrimaryCareOf
Doctor "N" -- Treats
Patient "M" -- Treats
Doctor "1" -- PrimaryCareOf
Patient "N" -- PrimaryCareOf
@enduml
93. Participation Constraints (Total vs Partial)
@startuml
title Course System
entity Course {
# course_id
title
}
entity Instructor {
# inst_id
name
}
entity Student {
# sid
name
}
relationship TaughtBy
relationship Takes
Course "1" == TaughtBy
Instructor "1" -- TaughtBy
Student "N" -- Takes
Course "M" == Takes
@enduml