12-UML类图

1. 关系

2. 类图

|205

可见性 符号 当前类 当前包 子孙类 其他包
private -
default/package/friendly 不写/~
protected #
public +

3. 类与类之间的关系

关系 说明 表示
继承(泛化) 继承关系,左:子类,右:父类 |100
实现 实现关系:左:实现类;右:接口 |100
关联 类与类的联结,【被指向方】作为【指向方】的属性 |100
组合 整体和部分关系,【被指向方】部分类,【指向方】整体类 |100
聚合 整体和部分关系,【被指向方】部分类,【指向方】整体类 |100
依赖 使用关系,【被指向方】使用类,【指向方】被使用类 |100

3.1. 泛化关系

3.2. 实现关系

3.3. 关联关系

单向关联

class Father {}

class Child {

    private Father m_father; // 私有成员变量
}

|634

双向关联

class Parent {
    private Child m_child;
}

class Child {
    private Parent m_father;  // 私有成员变量
}

有些软件这样表示:

自关联关系

class Node {
    private int m_data = 0;
    private Node m_prev = null;
    private Node m_next = null;
}

|344

3.4. 组合关系

class Root {
}

class Trunk {
}

class Branch {
}

class Leaf {
}

class Tree {
    private Root m_root;
    private Trunk m_trunk;
    private Branch m_branch;
    private Leaf m_leaf;

    public Tree() {
        m_root = new Root();
        m_trunk = new Trunk();
        m_branch = new Branch();
        m_leaf = new Leaf();
    }

    // 不需要写析构函数,Java会自动回收
}

public class Tree {
    private Root m_root;
    private Trunk m_trunk;
    private Branch m_branch;
    private Leaf m_leaf;

    public Tree() {
        m_root = new Root();
        m_trunk = new Trunk();
        m_branch = new Branch();
        m_leaf = new Leaf();
    }

    private static class Root {
    }

    private static class Trunk {
    }

    private static class Branch {
    }

    private static class Leaf {
    }
}

3.5. 聚合关系

// 植物类
class Plant {
    // 植物
}
// 动物类
class Animal {
    // 动物
}
// 水类
class Water {
    // 水
}
// 阳光类
class Sunshine {
    // 阳光
}
// 森林类
class Forest {
    private Plant plant;
    private Animal animal;
    private Water water;
    private Sunshine sunshine;
    public Forest(Plant plant, Animal animal, Water water, Sunshine sunshine) {
        this.plant = plant;
        this.animal = animal;
        this.water = water;
        this.sunshine = sunshine;
    }
}

3.6. 依赖关系

class Car {
    public void move() {
        // 车辆移动的逻辑
    }
}
class Driver {
    public void drive(Car car) {
        car.move();
    }
}

class Water {
    // 水的定义
}
class Air {
    // 空气的定义
}
class Soil {
    // 土壤的定义
}
class Tree {
    public void grow(Water w, Air a, Soil s) {
        System.out.println("借助 w 中的水分, s 中的养分和 a 中的二氧化碳, 我就可以茁壮成长了");
    }
}