• UML依赖关系详解


    1. 概述

    在统一建模语言(UML)中,依赖关系是一种重要的模型元素,用来表示一个事物(比如类、组件或包)依赖于另一个事物的情况。依赖关系通常表示一个事物的定义或实现部分地或完全依赖于另一个事物。

    2. 特点

    • 方向性:依赖关系是有方向的,表示一个元素使用或依赖另一个元素。
    • 动态性:依赖通常表示在运行时或在编译时的关系,不像关联那样通常表示更长久的关系。
    • 弱关系:相比于类的关联、聚合或组合,依赖是一种相对较弱的关系,通常用于表示非永久性的使用或交互。

    3. 依赖关系的类型

    UML 依赖关系可以细分为以下几种类型:

    3.1 使用依赖

    一个类(客户端)在其方法中使用另一个类(供应商)的实例。例如:

    • 一个 Car 类使用 Engine 类来提供动力。
    1. #include
    2. class Engine {
    3. public:
    4. void start() {
    5. std::cout << "Engine started" << std::endl;
    6. }
    7. void stop() {
    8. std::cout << "Engine stopped" << std::endl;
    9. }
    10. };
    11. class Car {
    12. public:
    13. Car() {
    14. engine = new Engine();
    15. }
    16. void start() {
    17. engine->start();
    18. }
    19. void stop() {
    20. engine->stop();
    21. }
    22. private:
    23. Engine* engine;
    24. };
    25. int main() {
    26. Car car;
    27. car.start();
    28. car.stop();
    29. return 0;
    30. }
    • 一个 ReportGenerator 类使用 DataSource 类来获取数据。
    1. #include
    2. #include
    3. class DataSource {
    4. public:
    5. virtual ~DataSource() {}
    6. virtual std::vector<int> getData() = 0;
    7. };
    8. class JdbcDataSource : public DataSource {
    9. public:
    10. std::vector<int> getData() override {
    11. std::cout << "Getting data from JDBC data source" << std::endl;
    12. return {1, 2, 3};
    13. }
    14. };
    15. class CsvDataSource : public DataSource {
    16. public:
    17. std::vector<int> getData() override {
    18. std::cout << "Getting data from CSV data source" << std::endl;
    19. return {4, 5, 6};
    20. }
    21. };
    22. class ReportGenerator {
    23. public:
    24. ReportGenerator(DataSource* dataSource) {
    25. this->dataSource = dataSource;
    26. }
    27. void generateReport() {
    28. std::vector<int> data = dataSource->getData();
    29. // ... 生成报表 ...
    30. }
    31. private:
    32. DataSource* dataSource;
    33. };
    34. int main() {
    35. // 使用 JDBC 数据源
    36. JdbcDataSource* jdbcDataSource = new JdbcDataSource();
    37. ReportGenerator reportGenerator1(jdbcDataSource);
    38. reportGenerator1.generateReport();
    39. // 使用 CSV 数据源
    40. CsvDataSource* csvDataSource = new CsvDataSource();
    41. ReportGenerator reportGenerator2(csvDataSource);
    42. reportGenerator2.generateReport();
    43. return 0;
    44. }

    3.2 创建依赖

    一个类负责创建另一个类的实例。例如:

    • 一个 Factory 类负责创建 Product 类的实例。
    1. #include
    2. class Product {
    3. public:
    4. virtual ~Product() {}
    5. virtual void doSomething() = 0;
    6. };
    7. class ConcreteProductA : public Product {
    8. public:
    9. void doSomething() override {
    10. std::cout << "ConcreteProductA do something" << std::endl;
    11. }
    12. };
    13. class ConcreteProductB : public Product {
    14. public:
    15. void doSomething() override {
    16. std::cout << "ConcreteProductB do something" << std::endl;
    17. }
    18. };
    19. class Factory {
    20. public:
    21. virtual ~Factory() {}
    22. virtual Product* createProduct() = 0;
    23. };
    24. class ConcreteFactoryA : public Factory {
    25. public:
    26. Product* createProduct() override {
    27. return new ConcreteProductA();
    28. }
    29. };
    30. class ConcreteFactoryB : public Factory {
    31. public:
    32. Product* createProduct() override {
    33. return new ConcreteProductB();
    34. }
    35. };
    36. int main() {
    37. Factory* factory = new ConcreteFactoryA();
    38. Product* productA = factory->createProduct();
    39. productA->doSomething();
    40. factory = new ConcreteFactoryB();
    41. Product* productB = factory->createProduct();
    42. productB->doSomething();
    43. return 0;
    44. }
    • 一个 Document 类负责创建 Paragraph 类的实例。
    1. #include
    2. #include
    3. class Section {
    4. public:
    5. Section(const std::string& text) {
    6. this->text = text;
    7. }
    8. void print() {
    9. std::cout << text << std::endl;
    10. }
    11. private:
    12. std::string text;
    13. };
    14. class Document {
    15. public:
    16. void addSection(const std::string& text) {
    17. sections.push_back(new Section(text));
    18. }
    19. void print() {
    20. for (Section* section : sections) {
    21. section->print();
    22. }
    23. }
    24. private:
    25. std::vector sections;
    26. };
    27. int main() {
    28. Document document;
    29. document.addSection("This is the first section.");
    30. document.addSection("This is the second section.");
    31. document.print();
    32. return 0;
    33. }

    3.3 参数依赖

    一个类的方法接受另一个类的实例作为参数。例如:

    • 一个 FileReader 类的方法接受一个 File 类的实例作为参数。
    1. #include
    2. #include
    3. class File {
    4. public:
    5. File(const std::string& path) {
    6. this->path = path;
    7. }
    8. const std::string& getPath() const {
    9. return path;
    10. }
    11. private:
    12. std::string path;
    13. };
    14. class FileReader {
    15. public:
    16. void readFile(const File& file) {
    17. std::ifstream ifs(file.getPath());
    18. if (ifs.is_open()) {
    19. std::string line;
    20. while (getline(ifs, line)) {
    21. std::cout << line << std::endl;
    22. }
    23. ifs.close();
    24. } else {
    25. std::cout << "Error opening file" << std::endl;
    26. }
    27. }
    28. };
    29. int main() {
    30. File file("C:/test.txt");
    31. FileReader fileReader;
    32. fileReader.readFile(file);
    33. return 0;
    34. }
    • 一个 List 类的 Add 方法接受一个要添加的元素作为参数。
    1. #include
    2. #include
    3. template <typename T>
    4. class List {
    5. public:
    6. void add(const T& element) {
    7. elements.push_back(element);
    8. }
    9. void print() {
    10. for (const T& element : elements) {
    11. std::cout << element << " ";
    12. }
    13. std::cout << std::endl;
    14. }
    15. private:
    16. std::vector elements;
    17. };
    18. int main() {
    19. List<int> list;
    20. list.add(1);
    21. list.add(2);
    22. list.add(3);
    23. list.print();
    24. return 0;
    25. }

    3.4 返回值依赖

    一个类的方法返回另一个类的实例。例如:

    • 一个 Database 类的方法返回一个 Connection 类的实例。
    1. #include
    2. class Connection {
    3. public:
    4. Connection() {
    5. std::cout << "Creating connection" << std::endl;
    6. }
    7. ~Connection() {
    8. std::cout << "Closing connection" << std::endl;
    9. }
    10. };
    11. class Database {
    12. public:
    13. Connection* getConnection() {
    14. return new Connection();
    15. }
    16. };
    17. int main() {
    18. Database database;
    19. Connection* connection = database.getConnection();
    20. // 使用连接...
    21. delete connection;
    22. return 0;
    23. }
    • 一个 Parser 类的方法返回一个 Document 类的实例。
    1. #include
    2. #include
    3. class Document {
    4. public:
    5. Document(const std::string& text) {
    6. this->text = text;
    7. }
    8. void print() {
    9. std::cout << text << std::endl;
    10. }
    11. private:
    12. std::string text;
    13. };
    14. class Parser {
    15. public:
    16. Document* parse(const std::string& filePath) {
    17. std::ifstream ifs(filePath);
    18. if (ifs.is_open()) {
    19. std::string text;
    20. while (getline(ifs, text)) {
    21. // ... 解析文本 ...
    22. }
    23. ifs.close();
    24. return new Document(text);
    25. } else {
    26. std::cout << "Error opening file" << std::endl;
    27. return nullptr;
    28. }
    29. }
    30. };
    31. int main() {
    32. Parser parser;
    33. Document* document = parser.parse("C:/test.txt");
    34. if (document != nullptr) {
    35. document->print();
    36. delete document;
    37. }
    38. return 0;
    39. }

    3.6 绑定依赖

    指模板实例化时,将模板类绑定到具体的参数上。

    类模板是指可以生成不同类型对象的类。类模板的实例化需要指定具体的类型参数。如果一个类的模板实例化依赖于另一个类,那么就表示该类模板依赖于另一个类。例如:

    • 一个 List 类模板可以生成不同类型元素的列表。
    1. #include
    2. #include
    3. template <typename T>
    4. class List {
    5. public:
    6. void add(const T& element) {
    7. elements.push_back(element);
    8. }
    9. void print() {
    10. for (const T& element : elements) {
    11. std::cout << element << " ";
    12. }
    13. std::cout << std::endl;
    14. }
    15. private:
    16. std::vector elements;
    17. };
    18. int main() {
    19. // 生成 int 型元素的列表
    20. List<int> list1;
    21. list1.add(1);
    22. list1.add(2);
    23. list1.add(3);
    24. list1.print();
    25. // 生成 string 型元素的列表
    26. List list2;
    27. list2.add("Hello");
    28. list2.add("World");
    29. list2.add("!");
    30. list2.print();
    31. return 0;
    32. }
    • 一个 Map 类模板可以生成不同类型键值对的映射。
    1. #include
    2. #include
    3. template <typename K, typename V>
    4. class Map {
    5. public:
    6. void add(const K& key, const V& value) {
    7. elements[key] = value;
    8. }
    9. void print() {
    10. for (const auto& pair : elements) {
    11. std::cout << pair.first << " -> " << pair.second << std::endl;
    12. }
    13. }
    14. private:
    15. std::map elements;
    16. };
    17. int main() {
    18. // 生成 int 型键值对的映射
    19. Map<int, int> map1;
    20. map1.add(1, 10);
    21. map1.add(2, 20);
    22. map1.add(3, 30);
    23. map1.print();
    24. // 生成 string 型键值对的映射
    25. Map map2;
    26. map2.add("Hello", "World");
    27. map2.add("Goodbye", "Cruel World");
    28. map2.print();
    29. return 0;
    30. }

    3.7 实现依赖

    实现关系是指一个类(实现类)承诺实现另一个类(接口)定义的契约。接口定义了一组方法和属性,但并不提供具体的实现,而是描述了一种行为规范。实现类则提供了这些方法和属性的具体实现。例如:

    • 一个 Animal 类定义一个 Speak 接口。
    • 一个 Dog 类实现 Animal 接口,并提供具体的 Speak 方法实现。
    1. #include
    2. class Animal {
    3. public:
    4. virtual void speak() = 0; // 纯虚函数,没有具体实现
    5. };
    6. class Dog : public Animal {
    7. public:
    8. void speak() override {
    9. std::cout << "Woof!" << std::endl;
    10. }
    11. };
    12. int main() {
    13. Dog dog;
    14. dog.speak();
    15. return 0;
    16. }

    实现关系的特点:

    • 契约: 接口定义了一种行为规范,实现类必须遵守该规范。
    • 实现: 实现类提供接口定义的方法和属性的具体实现。
    • 依赖: 实现类依赖于接口,因为需要根据接口定义来实现其功能。
    • 多态: 接口可以被多个类实现,从而提供不同的实现方式。

    3.8 扩展依赖

    扩展关系是一种 UML 关系类型,表示一个用例(扩展用例)在某些条件下扩展另一个用例(基本用例)的功能。扩展关系通常用于表示可选的、非必须的功能。

    扩展关系的关键点:

    • 扩展点: 基本用例中定义的点,扩展用例可以在该点插入其行为。
    • 可选性: 扩展用例不是基本用例必需的,只有在满足特定条件时才会执行。
    • 行为插入: 扩展用例的行为插入到基本用例的流程中,修改或补充基本用例的行为。
    • 类型: 扩展关系可以是包含扩展两种类型。

    扩展关系的应用场景:

    • 可选功能: 为基本用例添加可选功能,例如日志记录、错误处理等。
    • 条件性功能: 仅在满足特定条件时才执行的功能,例如权限控制、数据验证等。
    • 行为变异: 在不同情况下对基本用例行为进行不同的变异,例如不同的用户界面、不同的处理流程等。

    扩展关系的优点

    • 灵活性: 扩展关系可以使代码更加灵活,可以根据需要动态添加或删除功能。
    • 可扩展性: 扩展关系可以使代码更加可扩展,可以方便地添加新的功能。
    • 可维护性: 扩展关系可以使代码更加模块化和可维护性,可以将可选功能或条件性功能从基本用例中分离出来。

    扩展关系与其他关系的比较:

    • 包含关系: 包含关系表示一个用例包含另一个用例的所有功能,扩展关系则表示扩展用例只在某些情况下扩展基本用例的部分功能。
    • 继承关系: 继承关系表示一个类继承另一个类的所有属性和方法,扩展关系则表示两个用例之间是一种依赖关系。

    扩展关系示例:

    • 一个 登录 用例可以扩展一个 安全检查 用例,在需要进行安全检查时才执行安全检查功能。
    • 一个 下单 用例可以扩展一个 优惠计算 用例,在满足优惠条件时才计算优惠价格。
    • 一个文件上传用例可以扩展一个病毒扫描用例,在上传文件之前进行病毒扫描。
    1. #include
    2. class IControl {
    3. public:
    4. virtual void Click() = 0;
    5. protected:
    6. virtual void DoClick() = 0;
    7. };
    8. class Button : public IControl {
    9. public:
    10. void Click() {
    11. std::cout << "按钮被点击了!" << std::endl;
    12. DoClick();
    13. }
    14. protected:
    15. void DoClick() override {
    16. std::cout << "按钮执行点击操作!" << std::endl;
    17. }
    18. };
    19. class Security {
    20. public:
    21. virtual bool VerifyUser() = 0;
    22. protected:
    23. virtual void DoVerifyUser() = 0;
    24. };
    25. class LoginUseCase {
    26. public:
    27. void Execute() {
    28. std::cout << "登录用例正在执行..." << std::endl;
    29. // ...
    30. // 检查是否需要安全检查。
    31. if (isSecurityCheckNeeded) {
    32. Security security;
    33. if (!security.VerifyUser()) {
    34. std::cout << "登录失败:身份验证失败!" << std::endl;
    35. return;
    36. }
    37. }
    38. // ...
    39. }
    40. private:
    41. bool isSecurityCheckNeeded = true;
    42. };
    43. int main() {
    44. LoginUseCase loginUseCase;
    45. loginUseCase.Execute();
    46. return 0;
    47. }

    Control 类

    • Control 类是一个抽象类,代表一种控件。
    • Control 类定义了一个虚方法 Click(),用于触发控件的点击操作。

    Button 类

    • Button 类继承自 Control 类,代表一种按钮控件。
    • Button 类实现了 Click() 方法,用于执行按钮的点击操作。
    • 当用户点击按钮时,Button 类会执行 Click() 方法,并触发相应的业务逻辑。

    Security 类

    • Security 类继承自 Control 类,代表一种安全控制。
    • Security 类没有实现 Click() 方法,因为它不是用于点击操作的控件。
    • Security 类可以提供其他方法,用于执行安全检查操作。

    LoginUseCase 类

    • LoginUseCase 类是一个用例,代表登录用例。
    • LoginUseCase 类使用 Button 类和 Security 类来实现其功能。
    • LoginUseCase 类根据需要动态添加或删除 Button 类和 Security 类。

    1. #include
    2. class Order {
    3. public:
    4. virtual double calculatePrice() = 0; // 纯虚函数,没有具体实现
    5. protected:
    6. double originalPrice;
    7. public:
    8. Order(double originalPrice) {
    9. this->originalPrice = originalPrice;
    10. }
    11. };
    12. class DiscountCalculator {
    13. public:
    14. virtual bool isEligibleForDiscount(const Order& order) = 0; // 纯虚函数,没有具体实现
    15. virtual double calculateDiscount(const Order& order) = 0; // 纯虚函数,没有具体实现
    16. };
    17. class OrderWithDiscount : public Order {
    18. public:
    19. OrderWithDiscount(double originalPrice) : Order(originalPrice) {}
    20. double calculatePrice() override {
    21. DiscountCalculator calculator;
    22. if (calculator.isEligibleForDiscount(*this)) {
    23. return originalPrice - calculator.calculateDiscount(*this);
    24. } else {
    25. return originalPrice;
    26. }
    27. }
    28. };
    29. class SimpleDiscountCalculator : public DiscountCalculator {
    30. public:
    31. bool isEligibleForDiscount(const Order& order) override {
    32. return order.originalPrice >= 100;
    33. }
    34. double calculateDiscount(const Order& order) override {
    35. return order.originalPrice * 0.1;
    36. }
    37. };
    38. int main() {
    39. Order* order = new OrderWithDiscount(120);
    40. std::cout << "原价:" << order->originalPrice << std::endl;
    41. std::cout << "优惠价:" << order->calculatePrice() << std::endl;
    42. return 0;
    43. }

    在这个例子中,OrderWithDiscount 类扩展了 Order 类,并使用了 DiscountCalculator 类来计算优惠价格。


    1. #include
    2. #include
    3. class File {
    4. public:
    5. virtual bool isInfected() = 0; // 纯虚函数,没有具体实现
    6. protected:
    7. std::string path;
    8. public:
    9. File(const std::string& path) {
    10. this->path = path;
    11. }
    12. };
    13. class VirusScanner {
    14. public:
    15. virtual bool scan(const File& file) = 0; // 纯虚函数,没有具体实现
    16. };
    17. class FileUpload {
    18. public:
    19. virtual void upload(const File& file) = 0; // 纯虚函数,没有具体实现
    20. };
    21. class FileUploadWithVirusScan : public FileUpload {
    22. public:
    23. FileUploadWithVirusScan() {}
    24. void upload(const File& file) override {
    25. VirusScanner scanner;
    26. if (!scanner.scan(file)) {
    27. std::cout << "文件 " << file.path << " 含有病毒,无法上传" << std::endl;
    28. return;
    29. }
    30. // 上传文件...
    31. std::cout << "文件 " << file.path << " 上传成功" << std::endl;
    32. }
    33. };
    34. class SimpleVirusScanner : public VirusScanner {
    35. public:
    36. bool scan(const File& file) override {
    37. std::ifstream ifs(file.path);
    38. if (ifs.is_open()) {
    39. // 扫描文件内容...
    40. return true;
    41. } else {
    42. return false;
    43. }
    44. }
    45. };
    46. int main() {
    47. File* file = new File("C:/test.txt");
    48. FileUploadWithVirusScan uploader;
    49. uploader.upload(*file);
    50. return 0;
    51. }

    在这个例子中,FileUploadWithVirusScan 类扩展了 FileUpload 类,并使用了 VirusScanner 类来扫描文件是否含有病毒。

    4. 依赖关系的表示

    假设有一个ReportGenerator类,它负责生成报告,并使用DataSource类来获取所需的数据。在这种情况下,ReportGenerator依赖于DataSource,因为它需要DataSource提供的数据来完成其功能。在UML图中,这种依赖关系会用一条从ReportGenerator指向DataSource的带有开放箭头的虚线来表示。

    5. 注意事项

    • 依赖关系应该尽可能地弱,以便提高代码的模块性和可维护性。
    • 循环依赖关系应该避免,因为它会导致代码难以理解和维护。
    • 依赖关系应该在设计阶段仔细考虑,并进行必要的调整和优化。

  • 相关阅读:
    短视频矩阵系统/pc、小程序版独立原发源码开发搭建上线
    前端学习之:Vue 中使用 element UI 和 echarts 创建组件的步骤(echarts 的全局使用和组件内使用)
    字符串函数以及内存函数的模拟实现(超详细,全面理解字符串函数!!!)
    eProsima-fastdds简介
    python+nodejs+vue考研辅导网站系统
    市场饱和,你得抓住Android初级开发破局关键点---Framework
    高额补贴!武汉市科技型企业保证保险贷款补贴申报条件、流程和材料
    JeecgBoot 低代码平台 v3.6.0 大版本发布 —1024 程序员节快乐~
    Python之并发编程
    用了这款插件,零代码基础也能写代码你信吗?
  • 原文地址:https://blog.csdn.net/ChatCoding/article/details/136356232