[UML] NO.2 Basic knowledge that UML must understand (examples)

Table of contents

1. The composition of UML

1.1 Things

1.2 Relationship

1.3 Figure

2. Things

2.1 Structural things

2.1.1 Class

2.1.2 Interface

2.1.3 Collaboration

2.1.4 Use cases

2.1.5 Active class

2.1.6 Components

2.1.7 Node

2.2 Behavioral things

2.2.1 Interaction

2.2.2 State machine

2.2.3 Activities

2.3 Group things

Bag

2.4 Annotate things

3. Relationship

3.1 Dependencies

3.2 Relationship

3.3 Generalization relationship

3.4 Realizing relationships

4. Public mechanism


To learn some UML, you must first know what the main components of UML are.

It is recommended that you collect this article. I will add illustrations of examples in the future for one-stop learning.        

1. The composition of UML

The structure of UML includes three parts: things, relationships and diagrams. Here is their detailed explanation:

1.1 Things

Things in UML are also called modeling elements, including structural things, behavioral things, grouping things and annotation things.

  • Structural things: Elements that describe the static structure of the system, including classes, interfaces, collaborations, use cases, active classes, nodes, components, etc.
  • Behavioral things: Elements that describe dynamic behavior in the system, including state machines and interactions.
  • Grouping things: Describes how to organize a set of structural things and behavioral things together to form a larger unit, which is a package.
  • Annotation things: used to explain and illustrate elements in the model, this is annotation.

1.2 Relationship

Relationships in UML describe the connections between things, including association relationships, generalization relationships, implementation relationships, and dependency relationships.

  • Association relationship: describes the structural relationship between two classes, including aggregation and combination.
  • Generalization relationship: describes the inheritance relationship between classes, indicating that one class is a special case or type of another class.
  • Implementation relationship: Describes how a class implements an interface.
  • Dependency relationship: describes the semantic relationship between two model elements, where changes in one element (independent element) will affect the semantics of the other element (dependent element).

1.3 Figure

Diagrams in UML describe an aspect or perspective of the system, including static diagrams and dynamic diagrams.

  • Static diagrams: including class diagrams, object diagrams, package diagrams, component diagrams and deployment diagrams, etc., used to describe the static structure of the system.
  • Dynamic diagrams: including use case diagrams, activity diagrams, state diagrams, interaction diagrams (including sequence diagrams, communication diagrams and sequence diagrams), etc., used to describe the dynamic behavior of the system.

The above are the components of UML and their explanations. These elements together form the basis of UML, allowing us to use UML to model and analyze software.

If you just want to get an overview, then the above is the core information. If you want to know more, please read on.

2. Things

2.1 Structural things

2.1.1 Class

In UML, a class is a basic modeling element that describes a collection of objects with the same attributes, operations, relationships, and semantics. A class defines all the properties and behavior of a set of objects.

The definition of a class usually includes the following parts:

  • Class name: The name used to identify the class, usually using camel case naming.
  • Attributes: The attributes of a class describe the state of the class, that is, the data contained by the object. Each property has a name, type, and visibility (such as public, private, or protected).
  • Operation: The operation of a class describes the behavior that the class can perform, that is, the method or function of the object. Each operation has a name, parameter list, and return type. Actions can also have visibility.
  • Relationship: Classes can establish relationships with other classes, such as association relationships, generalization relationships, implementation relationships, and dependency relationships. These relationships describe interactions and connections between classes.

For example, consider a simple "dog" class, which might have the following definition:

Class name: Dog

Attributes:

  • name (String): dog’s name
  • age (int): dog’s age
  • breed (String): dog breed

operate:

  • bark(): dog barks
  • run(): dog run
  • eat(food: Food): Dog eats food

The "dog" class defines a class with three properties and three operations. In actual programming, this class can be instantiated as one or more "dog" objects, each of which has its own properties and behaviors.

In UML class diagrams, a class is usually represented by a rectangle, with the class name placed at the top of the rectangle, and attributes and operations placed in the middle and bottom of the rectangle respectively. Properties and operations can be preceded by visibility modifiers (+ for public, - for private, # for protected). Relationships usually connect related classes with lines, and the line is marked with the name of the relationship.

2.1.2 Interface

In UML, an interface (Interface) is a special class that defines a set of specifications for operations but does not implement these operations. The interface describes the behavior that a class should have, but does not care about how to implement these behaviors. An interface defines a contract that specifies the behavioral rules that a class must adhere to.

The definition of an interface usually includes the following parts:

  • Interface name: The name used to identify the interface, usually using camel case naming.
  • Operation: The operation of an interface is a set of methods or functions it defines. Each operation has a name, parameter list, and return type. Unlike a class, an interface only defines the signature of an operation without providing a concrete implementation.

For example, consider a simple "drawable" interface, which might have the following definition:

Interface name: Drawable

operate:

  • draw(): draw object

This "drawable" interface defines an interface with one operation, the "drawable object". Any class that implements this interface must provide a concrete implementation of the "draw()" method.

In actual programming, an interface can be implemented by a class, which means that the class must provide specific implementations of all operations defined in the interface. A class can implement multiple interfaces, which means it needs to provide implementations of operations defined in multiple interfaces.

In UML class diagrams, the interface is usually represented by a rectangle with the "interface" label, the interface name is placed at the top of the rectangle, and the operations are listed at the bottom of the rectangle. Unlike classes, interfaces have no attributes part. The implementation relationship usually uses a dotted line to connect the class that implements the interface and the interface itself, and the line is marked with keywords such as "implements" or "<<realize>>".

One of the benefits of using interfaces is that they provide a layer of abstraction that allows different classes to implement the same interface, thus achieving polymorphism. This means that different objects can be referenced using the same interface and the actual operations performed can be determined at runtime. This flexibility makes interfaces an important tool in object-oriented programming for defining and extending the behavior of a system.

2.1.3 Collaboration

In UML, collaboration refers to the interaction and cooperation between multiple classes, interfaces or other modeling elements to complete specific tasks. Collaboration describes the relationships between different modeling elements and their behavior in achieving a common goal.

The definition of collaboration usually includes the following components:

  • Actors: Collaboration involves multiple actors, which can be classes, interfaces, objects, or other modeling elements. Each participant plays a specific role in the collaboration and interacts with other participants.
  • Interaction: Interaction in collaboration refers to the process of passing messages, invoking operations, or sharing information between participants. These interactions can be synchronous or asynchronous, and can include various behaviors such as the invocation of methods, the firing of events, or the passing of data.
  • Relationships: Relationships in a collaboration describe the connections and dependencies between participants. These relationships can be association relationships, generalization relationships, implementation relationships, dependency relationships, or other UML-defined relationships. Relationships define how participants interact and collaborate with each other.
  • Scenario: Collaboration usually takes place in a specific scenario, that is, under a specific set of conditions and circumstances. Scenarios describe why collaboration occurs, the states of the participants, and the sequence of interactions between them.

For example, consider a simple online shopping system that includes classes such as Customer, Cart, and Order. In this system, customers can add items to their shopping cart and then place an order for the items in their shopping cart. This process involves collaboration between multiple classes.

Participants:

  • Customer: Represents a user in the system who has behaviors such as browsing products, adding products to the shopping cart, and generating orders.
  • Shopping Cart: Represents the customer's shopping cart, with actions such as adding items, removing items, and calculating the total price.
  • Order: Represents the order generated by the customer, with actions such as saving order information and processing payment.

Interaction:

  • Customers browse products and add selected items to their shopping cart.
  • The customer places an order for the items in the shopping cart.
  • Order processing payment and saving order information.

relation:

  • There is an associated relationship between customers and shopping carts. A customer can have multiple shopping carts, but each shopping cart can only belong to one customer.
  • There is a generalization relationship between the shopping cart and the order. The order is a specialized form of the shopping cart and inherits some attributes and behaviors of the shopping cart.

This simple online shopping system example demonstrates collaboration between classes, describing how they interact and cooperate in completing a purchase. In actual UML modeling, sequence diagrams, communication diagrams or activity diagrams can be used to visualize and describe the detailed process of collaboration.

Collaboration in UML describes the interaction and cooperation between multiple modeling elements to complete specific tasks. It involves elements such as actors, interactions, relationships, and scenarios. By understanding and modeling collaboration, you can better understand the dynamic behavior of your system and design effective software solutions.

2.1.4 Use cases

In UML, a use case is a model element that describes the function of a system. It represents the interaction between a system, subsystem or class and external users or other systems. Use cases capture the functional requirements that a system should perform and describe how the system interacts with external entities to achieve these functions.

The definition of use cases usually includes the following parts:

  • Use case name: The name used to identify the use case. It should describe the main function of the use case concisely and clearly.
  • Actor: An external entity that interacts with the use case, which can be a user, other system, or hardware device. Participants described their roles and responsibilities related to the use case.
  • Precondition: A condition or state that must be met before a use case can be executed. These conditions constrain the execution of the use case and ensure that the system is in an appropriate state before executing the use case.
  • Main success scenario: describes the main success path of the use case, that is, the execution process of the use case under normal circumstances. The main success scenario should clearly describe the steps and outcomes of the interaction between the actor and the system.
  • Expansion and exception scenarios: Describes the expansion path of the use case and the execution process under abnormal circumstances. These situations include error handling, abnormal input or abnormal status, etc. Extended and exception scenarios provide supplements to the main success scenario and ways to handle exceptions.

For example, consider a simple online library system that includes functions for users to log in, browse books, borrow books, and return books. Here is an example use case for the "Borrow Books" feature:

Use case name: Borrowing books

Participants: library users

Prerequisite: The user must be logged in and have borrowing rights.

Main success scenario:

  • The user selects the books they want to borrow.
  • The system checks the book's availability and the user's borrowing rights.
  • If the book is available and the user has permission, the system updates the book status to "Borrowed" and saves the borrowing information to the user's borrowing record.
  • The system displays a message that the borrowing was successful.

Extended and exceptional scenarios:

  • If the book is unavailable, the system displays a message that the book is unavailable and allows the user to select another book.
  • If the user does not have borrowing permission, the system displays a message indicating insufficient permissions and terminates the borrowing process.

This example shows how use cases describe the functional and interactive behavior of a system. By defining use cases, we can better understand the requirements and behavior of the system and ensure that user expectations and needs are met during the design and development process. In actual UML modeling, use case diagrams can be used to visualize and organize the relationships between use cases to better understand and communicate the functional requirements of the system.

2.1.5 Active class

In UML, an active class (Active Class) is a class that has a life cycle and can actively start and control its behavior. It describes a situation where objects have concurrent behavior and independent control flows. Active classes have a similar structure to traditional classes, but they are able to receive and process events, have their own threads, and interact concurrently with other active classes.

The definition of an active class usually includes the following parts:

  • Class names and attributes: Active classes have the same class names and attribute definitions as traditional classes. They can contain status information and other data members.
  • Behavior: The behavior of an active class is described by its operations (methods) and state machine. Operations define the behavior that an active class can perform, while a state machine describes the behavior of an active class in different states and the transitions between states.
  • Concurrency: Active classes have concurrency characteristics in that they can create their own threads and interact with other threads during execution. This means that objects of the active class can perform multiple operations at the same time.
  • Event handling: Active classes can receive and process external events. When an event occurs, the object of the active class will trigger the corresponding operation or state transition to respond to the event.

For example, consider a simple elevator control system where the elevator is an active class. Each elevator object has its own status (such as opening the door, closing the door, ascending, descending, etc.) and can respond to the passenger's button press event.

Class name: Elevator

Attributes:

  • currentFloor: current floor
  • targetFloor: target floor
  • state: the status of the elevator (opening the door, closing the door, etc.)

Behavior:

  • openDoor(): Open the elevator door
  • closeDoor(): close the elevator door
  • moveUp(): The elevator goes up one level
  • moveDown(): The elevator goes down one level

Concurrency:
The elevator object has its own thread that can receive and handle button press events from multiple passengers at different points in time.

Event handling:
When the passenger presses the button, the elevator object will trigger the corresponding operation to change its status and target floor, and start the movement process.

This example shows how active classes describe objects with lifecycle, concurrent behavior, and event handling capabilities. By defining active classes, we can better understand and model systems with concurrency and reactivity, and consider concurrency and synchronization issues during the design and development process. In actual UML modeling, state diagrams, sequence diagrams, etc. can be used to visualize and describe the behavior and interactions of active classes.

2.1.6 Components

In UML, a component is a replaceable physical component in a software system that encapsulates implementation and interacts with the external environment through a set of interfaces. Artifacts represent physical elements such as executables, libraries, frameworks, or plug-ins that are observable in the deployment and runtime environment.

The definition of a component usually includes the following parts:

  • Name and type: Each component has a unique name and type that is used to identify and classify the component. Types can be executable files, library files, other binary files, etc.

  • Interface: The component interacts with the external environment through the interface. An interface defines the services or operations provided by a component and specifies how it interacts with other components or system elements.

  • Implementation: Components encapsulate specific implementation details, which can be source code, binary code or other forms of implementation logic.

  • Dependencies: There may be dependencies between components, indicating that one component depends on the services or functions of another component. These dependencies can be compile-time dependencies or run-time dependencies.

For example, consider a simple web application that includes front-end and back-end components. The front-end component is responsible for the user interface and interaction logic, while the back-end component is responsible for data processing and business logic. Each component can be considered a building block.

In this example, the front-end component can be a JavaScript file in a web browser that provides the user interface and interactive functionality. The backend component can be a Java application on a web server that handles requests from the frontend and returns the corresponding data.

Frontend Component:

  • Name: Frontend.js
  • Type: JavaScript file
  • Interface: API that provides user interface and interactive functions
  • Implementation: JavaScript code that encapsulates front-end logic and interaction

Backend Component:

  • Name: Backend.jar
  • Type: Java application
  • Interface: Provides API for data processing and business logic
  • Implementation: Java code that encapsulates back-end logic and data processing

These components interact through the HTTP protocol. The front-end component sends an HTTP request to the back-end component and receives the HTTP response returned by the back-end component. This interaction defines the interfaces and dependencies between components.

In actual UML modeling, component diagrams can be used to visualize and describe the relationships and dependencies between components. Component diagrams show how different components in a system are connected and interact with each other and provide information about the physical organization and deployment of the components.

A component in UML is a physical component in a software system that encapsulates implementation and interacts with the external environment through interfaces. By defining components, we can better understand and organize the physical structure of the software system and ensure that the software system is deployed and run correctly in different environments.

2.1.7 Node

In UML, node (Node) represents a physical or logical resource in the runtime environment, which is the basic unit of system deployment and execution. Nodes can be computers, servers, devices, or other entities with processing, storage, and communication capabilities. Nodes describe the physical topology of the system and the software components that run on these nodes.

The definition of a node usually includes the following parts:

  • Name and type: Each node has a unique name and type that is used to identify and classify the node. Type can be computer, server, device, etc.
  • Computing resources: Nodes have computing resources, including processors, memory, storage devices, etc. These resources are used to execute and store software components.
  • Software components: One or more software components can be deployed and run on the node, including applications, middleware, operating systems, etc. These components interact with the node's computing resources to implement the system's functionality.
  • Connection relationship: communication and data transmission between nodes through connections. The connection relationship can be a network connection, a communication protocol, or other forms of connection.

For example, consider a simple distributed system that includes a web server, a database server, and client nodes. Each node has different capabilities and resources and interacts through network connections.

In this example, the web server node is responsible for processing web requests and generating responses, the database server node is responsible for storing and managing data, and the client node is the interface for users to interact with the system.

Web Server Node:

  • Name: WebServer
  • Type: Server
  • Computing resources: processor, memory, storage device
  • Software components: Web server software (such as Apache), application code, etc.

Database Server Node:

  • Name: DatabaseServer
  • Type: Server
  • Computing resources: processor, memory, storage device
  • Software components: database management system (such as MySQL), data storage, etc.

Client Node:

  • Name: Client
  • Type: computer or device
  • Computing resources: processor, memory, display device, etc.
  • Software components: client applications (such as web browsers), etc.

These nodes interact through network connections, and the web server node receives requests from client nodes and communicates with the database server node to obtain data. This interaction method defines the connection relationship between nodes and the data transmission method.

In actual UML modeling, a deployment diagram (Deployment Diagram) can be used to visualize and describe the relationships and connections between nodes. A deployment diagram shows the physical topology of the different nodes in the system and the deployment of software components running on these nodes. It provides information on how the system will be deployed and perform in a real-world environment.

In summary, nodes in UML represent physical or logical resources in the runtime environment, describing the physical topology of the system and the deployment of software components. By defining nodes, we can better understand the actual deployment and execution environment of the system and ensure that software components run in the right place and interact correctly with other components.

2.2 Behavioral things

2.2.1 Interaction

In UML, interaction describes the communication and collaboration between objects to complete specific tasks. Interaction emphasizes the dynamic behavior between objects during system execution, including message passing, operation invocation, and state changes. Interaction is one of the important concepts used in UML to describe the dynamic behavior of a system.

The definition of interaction usually includes the following parts:

  • Object: The object involved in the interaction is a class or instance in the system. These objects can be actors, controllers, business logic, etc. in the system.
  • Message: Message is the basic unit of communication between objects. Messages can be operation calls, event triggers, or other forms of communication. Messaging describes how objects collaborate and interact with each other.
  • Sequence: Objects in an interaction send and receive messages in a certain order. Sequence describes the timing and logical flow of interactions.
  • Scenario: Interaction occurs in a specific scenario, such as user operation, system response, exception handling, etc. Scenarios define the context and purpose of an interaction.

For example, consider a simple online shopping system that includes objects such as users, shopping carts, and orders. Users browse and add items to their shopping cart, then submit their order for checkout. This process involves interactions between multiple objects.

In this example, the user object sends a message to the shopping cart object to add items to the shopping cart. The shopping cart object updates the state and returns a confirmation message to the user object. Then, the user object sends a message to submit the order to the order object, and the order object processes the order information and returns the settlement result to the user object.

Interaction Example:

  • The User object sends the "Browse Products" message to the Product object.
  • The product object returns product details to the user object.
  • The user object sends an "add to cart" message to the shopping cart (Shopping Cart) object, along with information about the selected item.
  • The shopping cart object updates the shopping cart state and returns a confirmation message to the user object.
  • The user object sends a "submit order" message to the Order object, along with the product information in the shopping cart.
  • The order object processes the order information, performs settlement, and returns the settlement result to the user object.

In actual UML modeling, you can use Sequence Diagram or Collaboration Diagram to describe the detailed process of interaction. Sequence diagrams show the order and time relationships of message transfer between objects, while collaboration diagrams emphasize the structural relationships and collaboration methods between objects. These diagrams help us understand and visualize the dynamic behavior and interaction processes between objects in the system.

Interaction in UML describes the communication and collaboration between objects during system execution, including message passing, operation calls, and state changes. By defining interactions, we can better understand the dynamic behavior of the system and ensure that objects in the system can collaborate and interact correctly to achieve specific functions and tasks.

2.2.2 State machine

In UML, a state machine is a model used to describe the state changes of an object during its life cycle. It describes the behavior of an object in different states and the transition conditions between states. State machines are used to capture the reactions and behaviors of objects in different situations and are one of the important tools for modeling dynamic behavior in systems.

The definition of a state machine usually includes the following parts:

  • State: State is a certain condition or mode of an object during its life cycle. Each state defines the behavior and properties of the object in that state.
  • Transition: Transition is the process of change between states. It describes transition conditions and triggering events from one state to another. When the transition conditions are met, the object moves from the current state to the next state.
  • Event: An event is a trigger that causes a state transition. It can be an external event (such as a user action), an internal event (such as a system notification), or a time event (such as a timer expiration).
  • Action: An action is a behavior or activity performed during a state transition. It can be an action when entering or exiting a state, or an action performed during a specific state.

For example, consider a simple elevator system where the elevator has different states such as door opening, closing door, ascending and descending, etc. The elevator's status transitions based on the buttons pressed by the user and other conditions.

In this example, the elevator's state machine can be described as follows:

  • state:

    • Door Open: The elevator door is open and passengers can enter and exit.
    • Door Closed: The elevator door is closed and ready to move.
    • Up: The elevator is rising.
    • Down: The elevator is descending.
  • Conversion:

    • When the user presses the button outside the elevator or the floor button inside the elevator, it transitions from the "closed door" state to the "open door" state.
    • When the elevator door is closed and a target floor is selected, it transitions from the "open door" state to the "ascending" or "descending" state.
    • When the elevator reaches the target floor, it switches from the "rising" or "descending" state to the "open door" state.
  • event:

    • Button Pressed: The user presses the button outside the elevator or the floor button inside the elevator.
    • Door Closed: The elevator door is completely closed.
    • Floor Reached: The elevator reaches the target floor.
  • action:

    • Open the door: When entering the "open door" state, perform the action of opening the elevator door.
    • Close the door: When entering the "Close the door" state, perform the action of closing the elevator door.
    • Start movement: When entering the "rising" or "descending" state, perform the action of starting the elevator movement.
    • Stop movement: When entering the "open door" state, perform the action of stopping the elevator movement.

In actual UML modeling, a state diagram (State Diagram) can be used to describe the detailed model of the state machine. State diagrams show the different states, transition conditions, triggering events and actions of an object, helping us understand and visualize the state changes and behavior of the object. By defining a state machine, we can better capture and understand the dynamic behavior of objects in the system, and ensure that the system can correctly respond and handle various events and conditions in different states.

2.2.3 Activities

In UML, activity is a model element that describes the execution process of a system or object. An activity represents a sequence of steps and actions performed by a business process, operational process, or system function. Activities are typically used to describe workflows, task flows, or interaction processes in a system, and can contain elements such as decision points, concurrent execution, and synchronization points.

The definition of an activity usually includes the following parts:

  • Action: Action is the basic unit of activity and represents a step or operation in the execution process. Actions can be atomic or compound actions composed of multiple sub-actions.
  • Control Flow: Control flow describes the execution sequence and conditions between actions. It defines transitions and decision points between actions, as well as possible branches and merges.
  • Object Flow: Object flow describes the objects involved in activities and the relationships between them. It represents the transfer, use and transformation of objects between activities.
  • Decision Node: A decision point is a conditional judgment point in an activity, which determines the branch of the control flow based on specific conditions. It allows choosing different execution paths based on conditions.
  • Synchronization Point: A synchronization point is a waiting or rendezvous point in an activity, used to coordinate concurrently executed actions or sub-activities. It ensures that related actions reach a consistent state before continuing execution.

For example, consider the order processing process in a simple online shopping system. The process includes a series of steps such as receiving the order, verifying the order, processing payment and shipping.

In this example, the order processing process can be modeled as an activity, described as follows:

  • Receive Order: Receive order information submitted by customers.
  • Validate Order: Verify the completeness and validity of the order, such as checking inventory and price, etc.
  • Process Payment: Process customer payment information and interact with the payment system.
  • Shipping (Ship Order): Prepare goods and arrange shipping.

These steps can be represented as a sequence of actions, using control flow to describe the order and conditions between them. For example, if the order is invalid, you can use a decision point to interrupt the process and return an error message; if the payment is successful, you can continue to the shipping step; if the payment fails, you can retry the payment or cancel the order.

In actual UML modeling, activity diagrams (Activity Diagram) can be used to describe the detailed model of activities. Activity diagrams show elements such as actions, control flow, object flow, decision points, and synchronization points in activities, helping us understand and visualize the business processes and execution processes in the system. By defining activities, we can better organize and describe workflows and task flows in the system, as well as the relationships and interactions between them.

2.3 Group things

Bag

In UML, a package is a way of organizing and managing model elements. It provides a mechanism for grouping related elements together to form higher-level structure and modularity. Packages can be used to classify model elements, divide access rights, implement code reuse and modular design.

The definition of a package usually includes the following parts:

  • Name: Each package has a unique name that is used to identify and reference the package.
  • Elements: Packages can contain model elements such as other packages, classes, interfaces, components, use cases, relationships, etc. These elements are defined within the package and together with the package form a logical unit.
  • Visibility: A package can set the visibility of its internal elements to control other packages or elements' access to it. Common visibility levels are public, protected, and private.
  • Dependencies: Dependencies can exist between packages, indicating that one package depends on elements in another package. This dependency can have consequences when different packages interact and collaborate.

For example, consider a library management system, which includes multiple functional modules such as user management, book management, and borrowing management. In order to better organize these functional modules and related classes, we can use packages to group them.

In this example, we can create the following packages:

  • User Management Package: Contains user-related classes, such as user entity classes, user login verification classes, etc.
  • Book Management Package: Contains book-related classes, such as book entity classes, book catalog management classes, etc.
  • Borrowing Management Package: Contains classes related to borrowing, such as borrowing record classes, borrowing operation classes, etc.

By grouping related classes into different packages, we can achieve better code organization and modular design. Each package can be developed, tested and reused independently, reducing system complexity. At the same time, by using the visibility and dependencies of packages, we can control the interaction and access permissions between different packages, improving the security and maintainability of the system.

In actual UML modeling, package diagrams can be used to describe the structure and relationships of packages. Package diagram shows the dependencies and inclusion relationships between packages, helping us understand and visualize the module structure and organization of the system. By defining packages, we can better manage and organize the elements in the UML model and improve the efficiency and quality of modeling.

2.4 Annotate things

Commenting Elements are model elements used to provide explanatory, descriptive, or instructional information in the model. Annotating things does not directly affect the execution or behavior of the system, but can help developers, designers, and other stakeholders better understand and interpret the model.

The definition of annotations mainly includes the following aspects:

  • Text description: An annotation typically contains a text description that provides a description or explanation of an element or situation in the model. This text can be a brief note, a descriptive paragraph, or a more detailed explanation.
  • Associated objects: Annotation things can be associated with other elements in the model, such as classes, interfaces, use cases, activities, etc. Annotation things can provide additional information or explanations about specific model elements through associated objects.
  • Visual representation: In UML diagrams, annotated things are usually represented as graphical elements with annotation symbols (such as annotation boxes or cloud shapes). Annotation symbols contain annotation text and sometimes other formatting information (such as tags, colors, etc.).

Example:

Consider a simple online store system that contains a class called "Shopping Cart". To better explain the functionality and purpose of the shopping cart class, we can use annotation things to provide additional information.

In this example, we can create an annotation thing as described below:

  • Text description: "The shopping cart class is used to store the items selected by the user and provides functions for calculating the total price and settlement."
  • Associated object: Associate the annotation thing with the "Shopping Cart" class, indicating that this annotation is a description of the class.
  • Visual representation: In UML class diagrams, we can use graphical elements with annotation symbols to represent this annotation thing. An annotation symbol can be placed near the "Shopping Cart" class with an arrow pointing to it to show how they are related.

In actual UML modeling, annotating things can help improve the readability and understandability of the model. By adding explanatory and descriptive information to the model, annotating things facilitates communication and collaboration among team members and ensures a consistent understanding of the model. In addition, annotation things can be used to record design decisions, system constraints, or other important information for reference and review during the development process.

3. Relationship

3.1 Dependencies

Dependency is a way of describing the relationship between model elements, indicating that one element depends on the existence or behavior of another element. A dependency relationship indicates that one element depends on another element to some extent. When the dependent element changes, it may affect the elements that depend on it.

The definition of dependencies usually includes the following aspects:

  • Directionality: The dependency relationship is directional, indicating the direction of dependence. Dependencies are usually represented by a line with an arrow pointing to the dependent element.
  • Temporary: Dependencies are usually temporary and only exist in a specific context or scenario. Once the context changes, dependencies may change or disappear.
  • Visibility: Dependencies can have different visibility levels, such as public, private, etc. The visibility level determines how other elements can access and use the dependency.

Example:

Consider a simple online store system that includes a "User" class and an "Order" class. In this system, the "Order" class depends on the "User" class because each order must be associated with a user.

In this example we can describe the following dependencies:

  • The "Order" class depends on the "User" class: every order must have a user associated with it. This dependency can be expressed by adding an attribute (such as "User") to the "Order" class, which is a reference to the "User" class.
  • Relying on user information when creating an order: During the process of creating an order, you need to obtain the user's information (such as name, address, etc.). This means that some methods of the "Order" class (such as the method that creates the order) may call certain methods of the "User" class to obtain the necessary information. This dependency can be represented by using a dashed line with an arrow in the UML class diagram. The arrow points from the "Order" class to the "User" class, indicating the calling relationship.

In actual UML modeling, dependencies can be represented in different ways, such as using lines with arrows in class diagrams, using message flows in sequence diagrams, etc. In addition, you can also use some specific UML stereotypes (Stereotype) to further describe the nature of the dependency relationship, such as <<use>> indicating that one element uses the service or function of another element.

Understanding and managing dependencies is critical to the design and maintenance of software systems. By modeling and analyzing dependencies, developers can better understand the interactions and impacts between system components, allowing them to make sound design decisions and optimize the structure of the system. At the same time, reducing unnecessary dependencies and reducing coupling is also one of the key measures to improve software quality and maintainability.

3.2 Relationship

Association is a way of describing the structural relationship between model elements, indicating that there is some connection or connection between two or more classes. Associations describe the static structure between classes, that is, how objects are connected and how they refer to each other.

The definition of association usually includes the following aspects:

  1. Structural: Association relationship is a structural relationship between classes, describing the static connection between classes. It represents how objects between classes reference and connect to each other at runtime.
  2. Navigability: Association relationships can be navigable, that is, objects of one class can be accessed from objects of another class. This is represented by arrows on the relationship, pointing in the navigable direction.
  3. Multiplicity: The association relationship can have multiplicity, which describes the quantitative relationship between the objects of the classes at both ends of the association. Common multiplicities include one-to-one (1:1), one-to-many (1:N), many-to-one (N:1), and many-to-many (N:M).

Example:

Consider a simple online store system, which includes a "Customer" class and a "Product" class. In this system, customers can purchase multiple items, and each item can be purchased by multiple customers. Therefore, there is a many-to-many relationship between the "customer" class and the "product" class.

Specifically, this relationship can be described as follows:

  1. There is an association between the "customer" class and the "product" class: each customer can purchase multiple products, and each product can also be purchased by multiple customers. This means that there is a connection or relationship between the "customer" class and the "item" class.
  2. The association is navigable: an object of the "customer" class can access the object list of the "commodity" class it purchased, and vice versa. This can be represented by adding arrows on the relationship, pointing in the navigable direction.
  3. The relationship is multiplicity: since one customer can purchase multiple products, and one product can also be purchased by multiple customers, this is a many-to-many relationship. In UML class diagrams, you can use multiplicity markers (such as "*" to indicate multiple) to represent this quantitative relationship.

In actual UML modeling, the association relationship is usually represented by a solid line. You can add arrows on the association line to indicate navigation, and you can also add multiplicity markers at both ends of the association line to express the quantitative relationship. In addition, you can also use some specific UML stereotypes (Stereotype) to further describe the nature of the association relationship, such as <<owns>> indicating that an object of one class owns an object of another class.

By modeling association relationships, developers can better understand the connections and interactions between classes, thereby designing a more reasonable and flexible system structure. At the same time, association relationships also provide a basis for interaction and collaboration between classes, helping developers better organize and manage code.

3.3 Generalization relationship

In UML (Unified Modeling Language), generalization is a way to describe the inheritance relationship between classes, indicating that one class (subclass) inherits the attributes and attributes of another class (parent class). method. Generalization relationship, also known as "inheritance relationship", is an important relationship in object-oriented programming.

The definition of generalization relationships includes the following aspects:

  1. Inheritance: The generalization relationship means that the subclass inherits the attributes and methods of the parent class. Subclasses can reuse the parent class's code and add or override the parent's behavior when needed.
  2. Transitivity: The generalization relationship is transitive, that is, if class B inherits from class A, and class C inherits from class B, then class C also indirectly inherits from class A. This means that a subclass can inherit the properties and methods of its parent class and its parent class.
  3. Polymorphism: Generalization relationships support polymorphism, that is, subclasses can appear in the form of parent classes. This means that you can use a reference from the parent class to refer to an object of the subclass and call the appropriate method at runtime based on the type of the actual object.

Example:

Consider a simple animal classification system that includes a class "Animal" and a class "Dog". In this system, the "dog" class is a subclass of the "animal" class and inherits the attributes and methods of the "animal" class.

Specifically, this generalization relationship can be described as follows:

  1. The "animal" class is the parent class, and the "dog" class is a subclass: the "dog" class inherits the attributes and methods of the "animal" class, such as "bark" (bark), "run" (run), etc. This means that the class "dog" is a specialization or concretization of the class "animal".
  2. The generalization relationship is transitive: if there is a "ShepherdDog" class that is a subclass of the "Dog" class, then the "ShepherdDog" class also indirectly inherits from the "Animal" class. This means that the "Sheepdog" class can inherit the properties and methods of the "Animal" class and the "Dog" class.
  3. Generalization relationships support polymorphism: you can use a reference from the "Animal" class to refer to an object of the "Dog" class or the "Sheepdog" class, and call the corresponding method at runtime based on the type of the actual object. For example, you can define a method named "animalSound" as a virtual method in the "animal" class, and override it as "woof" in the "dog" class. ), overridden as a specific bark in the "Sheepdog" class. This way, when the "animalSound" method is called through a reference to the "Animal" class, the corresponding sound will be played based on the type of the actual object (dog or collie).

In actual UML modeling, the generalization relationship is usually represented by a solid line with a hollow triangular arrow pointing to the parent class. This hollow triangular arrow is the iconic symbol for a generalized relationship and is used to distinguish other types of relationships. In addition, you can add some labels or annotations on the generalization relationship line to provide additional information, such as access modifiers (public, protected, private) or constraints.

By modeling generalization relationships, developers can better organize and manage code and achieve code reuse and extension. Generalization relationships also provide a basis for building more complex systems. By abstracting common behaviors and attributes into parent classes, the design and implementation of subclasses can be simplified, and the maintainability and scalability of the system can be improved.

3.4 Realizing relationships

Realization is a way of describing the relationship between a class (or component) and its interface, indicating that the class implements the behavior defined by an interface. The implementation relationship is very important in object-oriented programming. It ensures that the class follows the contract specified by the interface, thereby achieving code decoupling and flexibility.

The definition of implementation relationships includes the following aspects:

  1. Contractuality: An interface defines the contract of a set of methods, namely method names, parameters and return types. The implementation relationship indicates that the class implements the methods specified by the interface, thus satisfying the contract of the interface.
  2. Multiplicity: A class can implement multiple interfaces, which means it can follow the contracts defined by multiple interfaces at the same time. This helps achieve code flexibility and scalability.
  3. Polymorphism: The implementation relationship supports polymorphism, that is, an interface can have multiple implementation classes. This means that you can use an interface reference to refer to an object of an implementing class and call the appropriate method at runtime based on the type of the actual object.

Example:

Consider a simple online payment system, which includes a "PaymentMethod" interface and a "CreditCardPayment" class. In this system, the "Credit Card Payment" class implements the "Payment Method" interface, thereby providing a specific payment method.

Specifically, this implementation relationship can be described as follows:

  1. The "payment method" interface defines a "pay" (pay) method, which accepts the payment amount as a parameter. This means that any class that implements the "payment method" interface needs to provide a concrete implementation of the "payment" method.
  2. The "Credit Card Payment" class implements the "Payment Method" interface: this means that the "Credit Card Payment" class must provide a concrete implementation of the "Payment" method. During the implementation process, the "Credit Card Payment" class may need to call bank APIs or other payment gateways to complete actual payment operations.
  3. The implementation relationship supports polymorphism: you can use a reference to the "Payment Method" interface to refer to an object of the "Credit Card Payment" class and call its "Payment" method at runtime. For example, you can define a method called "processPayment" that accepts a reference to the "payment method" interface as a parameter and internally calls the "payment" method of the reference. In this way, when different implementation class objects (such as "Credit Card Payment" class or objects of other implementation classes) are passed in, the method can call the corresponding payment method according to the type of the actual object.

In actual UML modeling, the implementation relationship is usually represented by a dotted line with a hollow triangular arrow pointing to the interface. This hollow triangular arrow is the iconic symbol for a realized relationship and is used to distinguish other types of relationships. In addition, you can add some tags or comments on the implementation relationship line to provide additional information, such as interface name or method signature.

By modeling implementation relationships, developers can better understand the relationship between classes and interfaces and ensure that classes implement the behavior specified by the interface. This helps achieve code decoupling and scalability while improving system flexibility and maintainability.

4. Public mechanism

(Omitted for now, waiting for examples) 

おすすめ

転載: blog.csdn.net/giszz/article/details/134936207