AgentSkillsCN

uml

适用于使用统一建模语言(UML)标准来建模软件系统。涵盖结构图与行为图类型、符号、关系、多重性、可见性与刻板印象。 适用场景:类图、序列图、活动图、状态机图、用例图、组件图、部署图、包图、对象图、UML 符号参考、关系类型、多重性、可见性修饰符、刻板印象。 不适用场景:文本式图表渲染(应使用 Mermaid.js、PlantUML 或 D2)、企业架构视图(应使用 TOGAF 或 ArchiMate)、数据建模(应使用 ERD)。

SKILL.md
--- frontmatter
name: uml
description: |
    Use when modeling software systems using the Unified Modeling Language (UML) standard. Covers structural and behavioral diagram types, notation, relationships, multiplicity, visibility, and stereotypes.
    USE FOR: class diagrams, sequence diagrams, activity diagrams, state machine diagrams, use case diagrams, component diagrams, deployment diagrams, package diagrams, object diagrams, UML notation reference, relationship types, multiplicity, visibility modifiers, stereotypes
    DO NOT USE FOR: text-based diagram rendering (use mermaidjs, plantuml, or d2), enterprise architecture views (use togaf or archimate), data modeling (use erd)
license: MIT
metadata:
  displayName: "UML"
  author: "Tyler-R-Kendrick"
compatibility: claude, copilot, cursor

UML — Unified Modeling Language

Overview

UML (Unified Modeling Language) is a standardized visual modeling language maintained by the Object Management Group (OMG). It provides a comprehensive set of diagram types for describing the structure, behavior, and interactions of software systems. UML is tool-agnostic — it defines notation and semantics, not rendering. For text-based rendering of UML diagrams, see the mermaidjs, plantuml, or d2 skills.

Diagram Categories

UML defines two broad categories: structural diagrams (static aspects) and behavioral diagrams (dynamic aspects).

Structural Diagrams

DiagramPurpose
ClassClasses, attributes, operations, and relationships
ObjectSnapshot of instances at a point in time
ComponentHigh-level components and their interfaces
PackageGrouping of model elements into namespaces
DeploymentPhysical deployment of artifacts to nodes
Composite StructureInternal structure of a class or component
ProfileExtension mechanisms for UML itself

Behavioral Diagrams

DiagramPurpose
Use CaseActor-system interactions (functional requirements)
SequenceMessage ordering between lifelines over time
ActivityWorkflow and process logic (flowchart-like)
State MachineStates and transitions for a single object
CommunicationObject interactions emphasizing links
Interaction OverviewHigh-level flow combining interaction fragments
TimingBehavior changes over time (real-time systems)

Class Diagram

The most widely used UML diagram. Models the static structure of a system by showing classes, their attributes, operations, and relationships.

Notation

code
┌────────────────────────────┐
│      <<stereotype>>        │
│       ClassName             │
├────────────────────────────┤
│ - privateField: Type       │
│ # protectedField: Type     │
│ + publicField: Type        │
│ ~ packageField: Type       │
├────────────────────────────┤
│ + publicMethod(): RetType  │
│ - privateMethod(): void    │
│ # protectedMethod(): void  │
│ + staticMethod(): Type     │  (underlined = static)
│ + abstractMethod()*: void  │  (* = abstract)
└────────────────────────────┘

Visibility Modifiers

SymbolVisibilityMeaning
+PublicAccessible from any class
-PrivateAccessible only within the class
#ProtectedAccessible within the class and subclasses
~PackageAccessible within the same package/namespace

Attribute Syntax

code
visibility name : Type [multiplicity] = defaultValue {constraint}

Examples:

code
- id : int
+ name : String
# items : List<Item> [0..*]
+ status : Status = ACTIVE {readOnly}

Operation Syntax

code
visibility name(param: Type, ...): ReturnType {constraint}

Examples:

code
+ calculateTotal(): Decimal
- validate(input: String): Boolean
+ findById(id: int): Customer {query}

Relationships

Relationship Types

RelationshipLineArrowheadMeaning
AssociationSolidOpen arrow or none"Uses" or "knows about"
Directed AssociationSolidOpen arrow (one end)One-way navigability
AggregationSolidOpen diamond"Has-a" (weak ownership, part can exist independently)
CompositionSolidFilled diamond"Owns-a" (strong ownership, part destroyed with whole)
Inheritance (Generalization)SolidOpen triangle"Is-a" (subclass extends superclass)
Realization (Implementation)DashedOpen triangleClass implements an interface
DependencyDashedOpen arrow"Uses temporarily" (parameter, local variable)

Visual Notation

code
Association:         A ──────────── B
Directed:            A ─────────> B
Aggregation:         A ◇────────── B    (A has B, B can exist alone)
Composition:         A ◆────────── B    (A owns B, B dies with A)
Inheritance:         A ────────▷ B      (A extends B)
Realization:         A - - - -▷ B       (A implements B)
Dependency:          A - - - -> B       (A depends on B)

Multiplicity

Multiplicity indicates how many instances participate in a relationship.

NotationMeaning
1Exactly one
0..1Zero or one (optional)
* or 0..*Zero or more
1..*One or more
nExactly n
n..mBetween n and m

Example:

code
Customer 1 ──────── 0..* Order
(One customer places zero or more orders)

Order 1 ──────── 1..* OrderItem
(One order contains one or more items)

Association Classes

When a relationship itself has attributes:

code
Student ────────── Course
            │
     ┌──────┴──────┐
     │ Enrollment   │
     ├──────────────┤
     │ grade: Grade  │
     │ semester: Str │
     └──────────────┘

Stereotypes

Stereotypes extend UML elements with domain-specific meaning. They are shown in guillemets (<< >>).

Common Stereotypes

StereotypeApplied ToMeaning
<<interface>>ClassDefines a contract (no implementation)
<<abstract>>ClassCannot be instantiated directly
<<enumeration>>ClassFixed set of named values
<<entity>>ClassDomain object with identity
<<value>>ClassImmutable value object
<<service>>ClassStateless service
<<repository>>ClassData access object
<<controller>>ClassHandles user input / HTTP requests
<<factory>>ClassCreates instances of other classes
<<singleton>>ClassOnly one instance exists
<<dataType>>ClassPure data structure
<<utility>>ClassStatic methods only

Sequence Diagram

Models the time-ordered exchange of messages between participants.

Notation

code
┌─────┐          ┌─────┐          ┌──────┐
│Actor│          │Obj A│          │Obj B │
└──┬──┘          └──┬──┘          └──┬───┘
   │   message()    │                │
   │───────────────>│                │
   │                │  delegate()    │
   │                │───────────────>│
   │                │   response     │
   │                │<─ ─ ─ ─ ─ ─ ─ │
   │   result       │                │
   │<─ ─ ─ ─ ─ ─ ─ │                │

Message Types

ArrowTypeMeaning
────>SynchronousCaller waits for response
- - ->Asynchronous / ReturnFire-and-forget or return value
────> (to self)Self-callObject calls its own method

Combined Fragments

FragmentKeywordPurpose
Alternativealt / elseIf/else branching
OptionoptIf (no else)
LooploopRepetition
ParallelparConcurrent execution
CriticalcriticalMutual exclusion region
BreakbreakExit enclosing fragment
ReferencerefReference to another sequence

Activity Diagram

Models workflows and process logic. Similar to flowcharts but with UML semantics for concurrency (fork/join) and swimlanes.

Notation

SymbolMeaning
Filled circleInitial node (start)
Rounded rectangleAction / Activity
DiamondDecision / Merge
Thick horizontal barFork (split) / Join (synchronize)
Circle with XFlow final (terminates one path)
BullseyeActivity final (ends all flows)

Example Structure

code
    (●)              ← Initial node
     │
  ┌──▼──┐
  │Receive│
  │Order  │
  └──┬──┘
     ◇                ← Decision
    / \
  Yes   No
  /       \
┌▼────┐  ┌▼─────┐
│Check │  │Reject │
│Stock │  │Order  │
└──┬──┘  └──┬───┘
   │        (◉)      ← Activity final
   ═══                ← Fork bar
  / \
┌▼──┐ ┌▼────────┐
│Pack│ │Process   │
│Item│ │Payment   │
└─┬─┘ └────┬────┘
   ═══                ← Join bar
    │
 ┌──▼──┐
 │ Ship │
 └──┬──┘
    (◉)

Swimlanes (Partitions)

Swimlanes divide activities by responsible actor or system.

code
│  Customer   │   System    │  Warehouse  │
│             │             │             │
│  (●)        │             │             │
│   │         │             │             │
│ Place Order │             │             │
│   │─────────┼──> Validate │             │
│             │   │─────────┼──> Pick Item│
│             │             │   │         │
│             │   Invoice ◄─┼───│         │
│             │   │         │   Ship      │
│  Receive ◄──┼───│         │             │
│   (◉)       │             │             │

State Machine Diagram

Models the lifecycle of a single object through its states and transitions.

Notation

SymbolMeaning
Filled circleInitial pseudo-state
Rounded rectangleState
ArrowTransition
BullseyeFinal state

Transition Syntax

code
trigger [guard] / effect
  • trigger: Event that causes the transition (e.g., submit, timeout)
  • guard: Boolean condition in brackets (e.g., [isValid])
  • effect: Action performed during transition (e.g., / sendEmail())

Example

code
(●)
 │
 ▼
┌──────────┐    submit       ┌────────────┐
│   Draft   │───────────────>│  Submitted  │
│           │                │             │
│entry/init │                │entry/notify │
└──────────┘                └──────┬─────┘
     ▲                            │
     │ reopen                     ◇
     │                      [valid]│ [invalid]
     │                     ┌──────▼─┐  │
     │                     │Approved │  │
     │                     │         │  │
     │                     └────┬───┘  │
     │                          │      ▼
     │                          │ ┌────────┐
     │                          │ │Rejected│
     └──────────────────────────┤ └────────┘
                                │
                                ▼
                              (◉)

Composite (Nested) States

States can contain substates to model complex behavior.

code
┌──────────── Active ──────────────┐
│  ┌─────────┐      ┌───────────┐ │
│  │Processing│─────>│ Validating│ │
│  └─────────┘      └───────────┘ │
└──────────────────────────────────┘

Use Case Diagram

Models functional requirements by showing actors and the use cases (features) they interact with.

Notation

SymbolMeaning
Stick figureActor (user or external system)
OvalUse case (feature / function)
RectangleSystem boundary
Solid lineAssociation (actor participates in use case)
Dashed arrow <<include>>Use case always includes another
Dashed arrow <<extend>>Use case optionally extends another
Open triangle arrowGeneralization (actor or use case inheritance)

Example

code
                    ┌─────── Online Store ────────┐
                    │                              │
  ┌────┐           │   (Browse Catalog)            │
  │User│───────────┼──>(Place Order)               │
  └──┬─┘           │       │                       │
     │              │       │ <<include>>           │
     │              │       ▼                       │
     │              │   (Process Payment)           │
     │              │       │                       │
     │              │       │ <<extend>>            │
     │              │       ▼                       │
     │              │   (Apply Coupon)              │
     │              │                              │
  ┌──┴──┐          │   (Manage Inventory)          │
  │Admin│──────────┼──>(Generate Reports)          │
  └─────┘          │                              │
                    └──────────────────────────────┘

Component Diagram

Shows the high-level components of a system and their interfaces.

Notation

SymbolMeaning
Rectangle with component iconComponent
Circle (lollipop)Provided interface
Half-circle (socket)Required interface
Dashed arrow <<use>>Usage dependency

Example

code
┌──────────────┐        ┌──────────────┐
│ <<component>> │        │ <<component>> │
│  Web UI       │──○─────┤  API Service  │
│               │  REST  │              │
└──────────────┘        └──────┬───────┘
                               │
                          ○────┘ IDataAccess
                          │
                   ┌──────┴───────┐
                   │ <<component>> │
                   │  Data Layer   │
                   └──────────────┘

Deployment Diagram

Maps software artifacts to hardware/infrastructure nodes.

Notation

SymbolMeaning
3D boxNode (server, VM, device, container)
Rectangle inside nodeArtifact (deployed software)
Dashed arrow <<deploy>>Deployment relationship

Example

code
┌──────────── <<device>> ────────────┐
│            Client Browser           │
│  ┌─────────────────────────┐       │
│  │ <<artifact>> SPA Bundle │       │
│  └─────────────────────────┘       │
└─────────────────┬──────────────────┘
                  │ HTTPS
┌─────────────────▼──────────────────┐
│     <<executionEnvironment>>        │
│            Kubernetes               │
│  ┌──────────────┐ ┌──────────────┐ │
│  │ <<artifact>> │ │ <<artifact>> │ │
│  │  API Pod     │ │  Worker Pod  │ │
│  └──────┬───────┘ └──────────────┘ │
└─────────┼──────────────────────────┘
          │ TCP/5432
┌─────────▼──────────────────────────┐
│       <<device>> DB Server          │
│  ┌─────────────────────────┐       │
│  │ <<artifact>> PostgreSQL │       │
│  └─────────────────────────┘       │
└────────────────────────────────────┘

Package Diagram

Groups model elements into namespaces to show code organization and dependencies.

code
┌──── Domain ────────────┐
│  ┌──────┐ ┌──────────┐ │
│  │Order │ │ Customer │ │
│  └──────┘ └──────────┘ │
└────────┬───────────────┘
         │ <<import>>
┌────────▼───────────────┐
│ Infrastructure          │
│  ┌────────────────────┐ │
│  │ OrderRepository    │ │
│  └────────────────────┘ │
└─────────────────────────┘

Object Diagram

A snapshot of instances and their relationships at a specific point in time. Uses the same notation as class diagrams but shows objects (instances) instead of classes.

code
┌──────────────────┐
│ order1 : Order    │
├──────────────────┤
│ id = 42           │
│ status = "ACTIVE" │
│ total = 99.50     │
└────────┬─────────┘
         │ contains
┌────────▼─────────┐
│ item1 : OrderItem │
├──────────────────┤
│ product = "Book"  │
│ quantity = 2      │
│ price = 49.75     │
└──────────────────┘

Constraints and Notes

Constraints

Constraints are boolean expressions enclosed in curly braces {} that restrict model elements.

code
{ordered}          - Collection is ordered
{unique}           - No duplicates allowed
{readOnly}         - Cannot be modified after initialization
{frozen}           - Cannot be changed after creation
{xor}              - Exactly one of the associations applies
{subset}           - One collection is a subset of another

Notes

Notes are attached to any UML element with a dashed line.

code
┌──────────────┐
│ Order         │ ─ ─ ─ ┐
├──────────────┤         │
│ + total: Dec │    ┌────┴──────────────┐
└──────────────┘    │ total must be >= 0 │
                    │ {total >= 0}       │
                    └───────────────────┘

Best Practices

  • Choose the right diagram for the audience. Use case diagrams for stakeholders, class diagrams for developers, deployment diagrams for operations.
  • Do not model everything. UML is a communication tool, not a code generation specification. Model only what adds clarity.
  • Keep diagrams focused. One diagram, one concern. A class diagram should not try to show every class in the system.
  • Use consistent naming. Class names in PascalCase, operations in camelCase, constants in UPPER_CASE.
  • Show multiplicity on all associations. Omitted multiplicity is ambiguous and forces readers to guess.
  • Distinguish aggregation from composition. Use composition (filled diamond) when the part cannot exist without the whole; use aggregation (open diamond) when it can.
  • Use stereotypes sparingly. Only add stereotypes that convey meaning your audience needs. Do not decorate every element.
  • Combine structural and behavioral diagrams. A class diagram shows what exists; a sequence diagram shows how it behaves. Together they tell the full story.
  • Use packages to manage complexity. For systems with many classes, organize them into packages first, then detail individual packages.
  • Validate against code. If your UML diverges from the actual code, the diagrams become misleading. Keep them synchronized or clearly label them as aspirational.
  • Prefer text-based tools. Use Mermaid, PlantUML, or D2 to write UML diagrams as code so they can be version-controlled and reviewed in pull requests.