深入理解系統:UML類圖

UML類圖

類圖(class diagram) 描述系統中的對象類型,以及存在于它們之間的各種靜態關系

正向工程(forward engineering)在編寫代碼之前畫UML圖。
逆向工程(reverse engineering)從已有代碼建造UML圖,目的是幫助人們理解代碼。

案例1:電商系統類圖

在這里插入圖片描述

# UML類圖元素:類、屬性、方法、繼承、關聯、聚合
from typing import Listclass User:def __init__(self, user_id: str, name: str):self.user_id = user_id  # 公有屬性self._name = name       # 保護屬性self.__password = ""    # 私有屬性def login(self, password: str) -> bool:  # 公有方法"""驗證用戶登錄"""return password == self.__passwordclass Customer(User):  # 繼承關系 (泛化)def __init__(self, user_id: str, name: str):super().__init__(user_id, name)self.cart = ShoppingCart()  # 組合關系 (強擁有)def place_order(self) -> Order:"""創建訂單"""return Order(self, self.cart.items)class Seller(User):  # 繼承關系def __init__(self, user_id: str, name: str, store: Store):super().__init__(user_id, name)self.store = store  # 關聯關系def add_product(self, product: Product):"""添加商品到店鋪"""self.store.products.append(product)class Product:def __init__(self, product_id: str, name: str, price: float):self.product_id = product_idself.name = nameself.price = priceclass ShoppingCart:def __init__(self):self.items: List[Product] = []  # 聚合關系 (弱擁有)def add_item(self, product: Product):self.items.append(product)def calculate_total(self) -> float:return sum(item.price for item in self.items)class Order:def __init__(self, customer: Customer, items: List[Product]):self.customer = customer  # 關聯關系self.items = itemsself.status = "Pending"def process_payment(self, payment: PaymentProcessor):  # 依賴關系payment.process(self.calculate_total())def calculate_total(self) -> float:return sum(item.price for item in self.items)class Store:def __init__(self, store_id: str, name: str):self.store_id = store_idself.name = nameself.products: List[Product] = []  # 聚合關系# 接口實現 (依賴倒置)
class PaymentProcessor(ABC):  # 抽象類/接口@abstractmethoddef process(self, amount: float):passclass CreditCardProcessor(PaymentProcessor):  # 實現關系def process(self, amount: float):print(f"Processing credit card payment: ${amount:.2f}")class PayPalProcessor(PaymentProcessor):  # 實現關系def process(self, amount: float):print(f"Processing PayPal payment: ${amount:.2f}")

案例2:車輛租賃系統類圖

在這里插入圖片描述

# UML類圖元素:抽象類、枚舉、組合、聚合、依賴
from abc import ABC, abstractmethod
from enum import Enum
from datetime import dateclass VehicleType(Enum):  # 枚舉類CAR = 1TRUCK = 2SUV = 3MOTORCYCLE = 4class AbstractVehicle(ABC):  # 抽象類def __init__(self, license_plate: str, model: str, year: int):self.license_plate = license_plateself.model = modelself.year = yearself.available = True@abstractmethoddef get_rental_rate(self) -> float:passclass Car(AbstractVehicle):  # 繼承def __init__(self, license_plate: str, model: str, year: int, seats: int):super().__init__(license_plate, model, year)self.seats = seatsdef get_rental_rate(self) -> float:  # 實現抽象方法return 50.0 + (self.seats * 5)class Truck(AbstractVehicle):  # 繼承def __init__(self, license_plate: str, model: str, year: int, capacity: float):super().__init__(license_plate, model, year)self.capacity = capacity  # 載重能力(噸)def get_rental_rate(self) -> float:return 100.0 + (self.capacity * 20)class RentalAgency:def __init__(self, name: str):self.name = nameself.fleet: List[AbstractVehicle] = []  # 聚合self.rentals: List[RentalContract] = []  # 組合def add_vehicle(self, vehicle: AbstractVehicle):self.fleet.append(vehicle)def rent_vehicle(self, customer: Customer, vehicle: AbstractVehicle, start_date: date, end_date: date):if vehicle.available:contract = RentalContract(customer, vehicle, start_date, end_date)self.rentals.append(contract)vehicle.available = Falsereturn contractreturn Noneclass Customer:def __init__(self, customer_id: str, name: str):self.customer_id = customer_idself.name = nameself.license_number = ""class RentalContract:  # 組合類def __init__(self, customer: Customer, vehicle: AbstractVehicle, start_date: date, end_date: date):self.customer = customerself.vehicle = vehicleself.start_date = start_dateself.end_date = end_dateself.total_cost = self.calculate_cost()def calculate_cost(self) -> float:days = (self.end_date - self.start_date).daysreturn days * self.vehicle.get_rental_rate()def generate_invoice(self, printer: InvoicePrinter):  # 依賴關系printer.print_invoice(self)class InvoicePrinter:  # 工具類def print_invoice(self, contract: RentalContract):print(f"Invoice for {contract.customer.name}")print(f"Vehicle: {contract.vehicle.model}")print(f"Total: ${contract.total_cost:.2f}")

案例3:學校管理系統類圖

在這里插入圖片描述

# UML類圖元素:多重繼承、接口實現、依賴、關聯
from abc import ABC, abstractmethod
from datetime import dateclass Person:def __init__(self, name: str, birth_date: date):self.name = nameself.birth_date = birth_datedef get_age(self) -> int:today = date.today()return today.year - self.birth_date.yearclass Researcher(ABC):  # 接口@abstractmethoddef conduct_research(self, topic: str):passclass Teacher(Person):  # 單繼承def __init__(self, name: str, birth_date: date, department: str):super().__init__(name, birth_date)self.department = departmentself.courses: List[Course] = []  # 雙向關聯def assign_course(self, course: 'Course'):self.courses.append(course)course.teacher = selfclass Professor(Teacher, Researcher):  # 多重繼承def __init__(self, name: str, birth_date: date, department: str, title: str):Teacher.__init__(self, name, birth_date, department)self.title = titledef conduct_research(self, topic: str):  # 實現接口print(f"Conducting research on {topic}")def supervise_phd(self, student: 'PhdStudent'):student.advisor = selfclass Student(Person):def __init__(self, name: str, birth_date: date, student_id: str):super().__init__(name, birth_date)self.student_id = student_idself.enrolled_courses: List['Course'] = []  # 關聯def enroll(self, course: 'Course'):self.enrolled_courses.append(course)course.students.append(self)class PhdStudent(Student, Researcher):  # 多重繼承def __init__(self, name: str, birth_date: date, student_id: str, research_topic: str):Student.__init__(self, name, birth_date, student_id)self.research_topic = research_topicself.advisor: Professor = None  # 關聯def conduct_research(self, topic: str):  # 實現接口print(f"Conducting PhD research on {topic}")class Course:def __init__(self, course_code: str, name: str):self.course_code = course_codeself.name = nameself.teacher: Teacher = None  # 雙向關聯self.students: List[Student] = []  # 雙向關聯def add_student(self, student: Student):self.students.append(student)student.enrolled_courses.append(self)class Department:def __init__(self, name: str):self.name = nameself.faculty: List[Teacher] = []  # 聚合self.courses: List[Course] = []  # 聚合def hire_teacher(self, teacher: Teacher):self.faculty.append(teacher)def add_course(self, course: Course):self.courses.append(course)class EnrollmentSystem:  # 依賴多個類def enroll_student(self, student: Student, course: Course):if student not in course.students:student.enroll(course)return Truereturn False

綜合案例:帶抽象接口和靜態方法的電商系統

在這里插入圖片描述

from abc import ABC, abstractmethod
from datetime import datetime# 抽象接口:日志服務
class ILogger(ABC):@abstractmethoddef log(self, message: str):pass# 實現接口的類
class ConsoleLogger(ILogger):def log(self, message: str):print(f"[{datetime.now()}] {message}")class FileLogger(ILogger):def __init__(self, filename: str):self.filename = filenamedef log(self, message: str):with open(self.filename, "a") as file:file.write(f"[{datetime.now()}] {message}\n")# 帶靜態方法的工具類
class ValidationUtils:@staticmethoddef is_valid_email(email: str) -> bool:return "@" in email and "." in email.split("@")[-1]@staticmethoddef is_valid_phone(phone: str) -> bool:return phone.isdigit() and len(phone) >= 7# 使用接口和靜態方法的類
class UserService:def __init__(self, logger: ILogger):self.logger = loggerdef register_user(self, name: str, email: str, phone: str):# 使用靜態方法驗證if not ValidationUtils.is_valid_email(email):self.logger.log(f"Invalid email: {email}")return Falseif not ValidationUtils.is_valid_phone(phone):self.logger.log(f"Invalid phone: {phone}")return False# 注冊邏輯...self.logger.log(f"User {name} registered with {email}")return True# 工廠類(使用靜態方法創建對象)
class LoggerFactory:@staticmethoddef create_logger(logger_type: str) -> ILogger:if logger_type == "console":return ConsoleLogger()elif logger_type == "file":return FileLogger("app.log")else:raise ValueError("Invalid logger type")

UML類圖要素總結

UML要素Python代碼表現UML符號說明
類(Class)class Person:矩形框包含類名、屬性和方法
抽象類class AbstractVehicle(ABC):斜體類名包含抽象方法
接口class Interface(ABC): + @abstractmethod<<interface>> + 斜體名稱只包含抽象方法
屬性self.name: str+name: str+公有, -私有, #保護
方法def get_age(self):
靜態方法: @staticmethod 裝飾器
類方法:@classmethod 裝飾器
抽象方法: @abstractmethod 裝飾器
+get_age(): int
靜態方法:{static} 標記或方法名下劃線
類方法:{classmethod} 標記
抽象方法:{abstract} 標記 + 斜體方法名
類行為定義
繼承class Teacher(Person):空心三角+實線泛化關系(is-a)
實現class Professor(Researcher):空心三角+虛線實現接口方法
組合一對一:self.cart = ShoppingCart()
一對多:self.car=[Wheel(),Wheel(),Wheel(),Wheel(),Engine()]
實心菱形+實線強擁有關系(同生命周期)
聚合self.fleet: List[Vehicle] = []空心菱形+實線弱擁有關系(可獨立存在)
關聯self.teacher: Teacher = None實線箭頭對象間持久引用關系
依賴def process_payment(payment):虛線箭頭臨時使用(方法參數或局部變量中)
枚舉class VehicleType(Enum):<<enumeration>>固定值集合
多重繼承class Professor(Teacher, Researcher):多個空心三角繼承多個父類

一些細節

關于【箭頭方向】

箭頭方向在UML中表示導航性(Navigability):

箭頭類型表示代碼等價
無箭頭雙向導航(默認)雙方相互持有引用
單向導航只有源頭類知道目標類
?雙向導航雙方相互持有引用
?/?箭頭端為被引用方箭頭指向的類是被持有的類

關于類關系的虛實

以下是對類圖中類關系圖形的完整總結,重點說明實心/空心、實線/虛線的區別:

1. 實線 vs 虛線
線條類型關系強度生命周期代碼對應典型關系
實線強關系可能綁定成員變量(屬性)關聯、聚合、組合
虛線弱關系無綁定方法參數/局部變量依賴、接口實現
2. 實心 vs 空心
填充類型所有權關系強度典型符號位置代表關系
實心強所有權最強菱形端組合關系
空心弱所有權中等菱形端/三角端聚合/繼承/實現
完整關系對比圖

在這里插入圖片描述

關于【多重性】

多重性定義對象之間的數量關系,常見表示法:

表示法含義示例說明
1恰好1個每個人有1個心臟(組合關系)
0..10或1個學生可能有0或1個導師(關聯關系)
1..*1個或多個訂單必須包含至少1個商品(組合關系)
0..*0或多個部門可以有0或多個員工(聚合關系)
n恰好n個三角形有3條邊(組合關系)
m..nm到n個課程有3-50名學生(關聯關系)
*無限多個(同0..*社交媒體用戶有多個好友(關聯關系)

匯總

要素類型UML表示法代碼表現多重性箭頭方向生命周期關系
類(Class)矩形框(類名、屬性、方法)class MyClass:不適用獨立存在
抽象類類名斜體class MyClass(ABC):不適用獨立存在
接口<<interface>> + 類框或圓圈class MyInterface(ABC):不適用獨立存在
枚舉<<enumeration>> + 枚舉值class MyEnum(Enum):不適用獨立存在
屬性[可見性] 屬性名: 類型 [= 默認值]self.attr = value不適用隨對象存在
方法[可見性] 方法名(參數): 返回類型def method(self):不適用隨對象存在
抽象方法斜體或{abstract}@abstractmethod不適用隨抽象類存在
靜態方法{static} 或下劃線@staticmethod不適用類加載時存在
類方法{classmethod}@classmethod不適用類加載時存在
繼承(泛化)空心三角箭頭 + 實線class Child(Parent):不適用子類→父類子類依賴父類
接口實現空心三角箭頭 + 虛線實現接口所有方法不適用實現類→接口實現類依賴接口
關聯實線(可帶箭頭)類屬性為另一類對象兩端可設置可選(表示導航方向)相互獨立
聚合空心菱形 + 實線外部傳入對象(self.parts = [ext_obj])整體端通常為1菱形→整體部分可獨立于整體
組合實心菱形 + 實線內部創建對象(self.part = Part())整體端通常為1菱形→整體部分依賴整體
依賴虛線箭頭局部變量/參數/靜態調用不適用使用方→被依賴方臨時關系

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/84077.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/84077.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/84077.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

DeepSeek12-Open WebUI 知識庫配置詳細步驟

&#x1f4da; Open WebUI 知識庫配置詳細步驟&#xff08;中英文對照&#xff09; &#x1f310; 界面語言切換 # 首次登錄后切換語言&#xff1a; 1. 點擊左下角用戶頭像 → Settings 2. 在 "General" 選項卡找到 "Language" 3. 選擇 中文(簡體)/Engli…

Python網絡設備批量配置腳本解析

目錄 腳本概述 代碼解析 導入模塊 日志配置 核心函數config_device 主程序邏輯 使用說明 腳本優化建議 完整代碼 腳本概述 這是一個使用Python編寫的網絡設備批量配置腳本&#xff0c;主要功能是通過SSH協議批量登錄多臺網絡設備&#xff08;如路由器、交換機等&…

Z-FOLD: A Frustratingly Easy Post-Training Quantization Scheme for LLMs

文章目錄 摘要1 引言2 相關工作2.1 量化2.2 大型語言模型的量化 3 Z-FOLD3.1 新引入的參數 ζ3.2 參數整合&#xff08;ζ 折疊&#xff09;3.3 使用校準集的微調 4 實驗4.1 實驗設置4.2 與其他方法的比較4.3 Z-FOLD 的泛化能力4.4 Z-FOLD 的可移植性4.5 消融研究 5 結論6 限制…

交流電機深度解析:從基礎到實戰的全面指南

簡介 交流電機作為現代工業中不可或缺的動力設備,廣泛應用于各個領域。本文將帶你深入了解交流電機,從最基礎的概念和工作原理開始,逐步介紹其類型、結構、關鍵參數等基礎知識。同時,我們會探討交流電機在企業級開發研發中的技術實戰,包括控制技術、調速方法、建模與仿真…

【靶場】XXE-Lab xxe漏洞

前言 學習xxe漏洞,搭了個XXE-Lab的靶場 一、搭建靶場 現在需要登錄,不知道用戶名密碼,先隨便試試抓包 二、判斷是否存在xxe漏洞 1.首先登錄抓包 看到xml數據解析,由此判斷和xxe漏洞有關,但還不確定xxe漏洞是否存在。 2.嘗試xxe 漏洞 判斷是否存在xxe漏洞 A.send to …

【C++特殊工具與技術】優化內存分配(三):operator new函數和opertor delete函數

目錄 一、基礎概念&#xff1a;operator new與operator delete的本質 1.1 標準庫提供的operator new接口 1.2 標準庫operator delete的接口 1.3 關鍵特性總結 二、new表達式與operator new的調用鏈解析 2.1 new表達式的底層步驟 2.2 示例&#xff1a;觀察new表達式的調用…

[c#]判定當前軟件是否用管理員權限打開

有時一些軟件的邏輯中需要使用管理員權限對某些文件進行修改時&#xff0c;那么該軟件在執行或者打開的場合&#xff0c;就需要用使用管理員身份運行才能達到效果。那么在c#里&#xff0c;如何判定該軟件是否是對管理員身份運的呢&#xff1f; 1.取得當前的windows用戶。 2.取得…

如果在main中拋出異常,該如何處理

#采用 setDefaultUncaughtExceptionHandler 進行全局兜底 public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> { System.err.println("全局捕獲異常: " ex.getMessage()); ex.printStackTrace(); System.exi…

HBM 讀的那些事

如下所示&#xff0c;為HBM讀的時序。注意這里說的HBM是和HBM3是有區別的. RL 的配置,是通過MR2來實現的 WDQS貌似和CK同頻。這幅圖告訴你&#xff0c;WDQS和CK的源頭是一樣的&#xff0c;都來自PLL&#xff0c;而且中間沒有經過倍頻操作。所以兩者頻率基本是一致的。這是HBM的…

省略號和可變參數模板

本文主要介紹如何展開可變參數的參數包 1.C語言的va_list展開可變參數 #include <iostream> #include <cstdarg>void printNumbers(int count, ...) {// 聲明va_list類型的變量va_list args;// 使用va_start將可變參數寫入變量argsva_start(args, count);for (in…

三十五、面向對象底層邏輯-Spring MVC中AbstractXlsxStreamingView的設計

在Web應用開發中&#xff0c;大數據量的Excel導出功能是常見需求。傳統Apache POI的XSSF實現方式在處理超大數據集時&#xff0c;會因全量加載到內存導致OOM&#xff08;內存溢出&#xff09;問題。Spring MVC提供的AbstractXlsxStreamingView通過流式處理機制&#xff0c;有效…

【大模型:知識圖譜】--3.py2neo連接圖數據庫neo4j

【圖數據庫】--Neo4j 安裝_neo4j安裝-CSDN博客 需要打開圖數據庫Neo4j&#xff0c; neo4j console 目錄 1.圖數據庫--連接 2.圖數據庫--操作 2.1.創建節點 2.2.刪除節點 2.3.增改屬性 2.4.建立關系 2.5.查詢節點 2.6.查詢關系 3.圖數據庫--實例 1.圖數據庫--連接 fr…

基于dify的營養分析工作流:3分鐘生成個人營養分析報告

你去醫院做體檢&#xff0c;需要多久拿到體檢報告呢&#xff1f;醫院會為每位病人做一份多維度的健康報告嗎&#xff1f;"人工報告需1小時/份&#xff1f;數據誤差率高達35%&#xff1f;傳統工具無法個性化&#xff1f; Dify工作流AI模型的組合拳&#xff0c;正在重塑健康…

Web后端基礎(基礎知識)

BS架構&#xff1a;Browser/Server&#xff0c;瀏覽器/服務器架構模式。客戶端只需要瀏覽器&#xff0c;應用程序的邏輯和數據都存儲在服務端。 優點&#xff1a;維護方便缺點&#xff1a;體驗一般 CS架構&#xff1a;Client/Server&#xff0c;客戶端/服務器架構模式。需要單獨…

MySQL(56)什么是復合索引?

復合索引&#xff08;Composite Index&#xff09;&#xff0c;也稱為多列索引&#xff0c;是在數據庫表的多列上創建的索引。它可以提高涉及多個列的查詢性能&#xff0c;通過組合多個列的值來索引數據。復合索引特別適用于需要同時過濾多列的查詢。 復合索引的優點 提高多列…

高并發下的緩存擊穿/雪崩解決方案

有效解決緩存擊穿和雪崩的方法包括&#xff1a;1. 使用互斥鎖處理緩存擊穿&#xff1b;2. 采用熔斷器模式防止雪崩&#xff1b;3. 實施緩存預熱和降級策略&#xff1b;4. 利用分片和多級緩存分散請求壓力。這些方法各有優劣&#xff0c;需根據實際業務場景靈活調整和結合使用。…

【讀論文】OpenAI o3與o4系統模型技術報告解讀

回顧一下,4月16日,OpenAI發布了一份關于其o系列新模型——OpenAI o3和OpenAI o4-mini——的System Card。這份文檔不僅揭示了這兩款模型在推理能力和工具使用方面的顯著進步,也詳細闡述了其訓練方法、數據來源、安全評估以及在圖像理解生成、數學推理等多個核心領域的表現。…

第1課、LangChain 介紹

LangChain 介紹 LangChain 是一個以大語言模型&#xff08;LLM, Large Language Model&#xff09;為核心的開發框架&#xff0c;旨在幫助開發者高效地將如 GPT-4 等大型語言模型與外部數據源和計算資源集成&#xff0c;構建智能化應用。 1.1 工作原理 如上圖所示&#xff…

【論文閱讀28】-CNN-BiLSTM-Attention-(2024)

本文把滑坡位移序列拆開、篩優質因子&#xff0c;再用 CNN-BiLSTM-Attention 來動態預測每個子序列&#xff0c;最后重構出總位移&#xff0c;預測效果超越傳統模型。 文章目錄 1 引言2 方法2.1 位移時間序列加性模型2.2 變分模態分解 (VMD) 具體步驟2.3.1 樣本熵&#xff08;S…

[論文閱讀] 人工智能+軟件工程(軟件測試) | 當大語言模型遇上APP測試:SCENGEN如何讓手機應用更靠譜

當大語言模型遇上APP測試&#xff1a;SCENGEN如何讓手機應用更靠譜&#xff1f; 一、論文基礎信息 論文標題&#xff1a;LLM-Guided Scenario-based GUI Testing&#xff08;《大語言模型引導的基于場景的GUI測試》&#xff09;作者及機構&#xff1a;Shengcheng Yu等&#x…