UML,全称 Unified Modeling Language,统一建模语言。而UML图分为用例图、类图、对象图、状态图、活动图、时序图、协作图、构件图、部署图等9种图。
UML 类图中有六种关系,分别是依赖关系、关联关系、聚合关系、组合关系、实现关系、泛化关系。在JS中,其中泛化关系和关联关系比较常用,后续主要讲这两个关系。
一、类图
在类图中,类的成员变量和方法前面的修饰符有 public、private、protected、default,在 UML 类图中分别用 +、-、#、~ 表示。如图所示:
- 第一行写的是类的名字;
- 第二行写的是类所有的属性;
- 第三行写的是类所有的方法;

举例:
class People {name: string;private age: number;protected weight: number;constructor(name, age, weight) {this.name = name;this.age = age;this.weight = weight;}getInfo() {console.log(`My name is ${this.name}`);this.getAge();}private getAge() {console.log(`My age is ${this.age}`);}protected getWeight() {console.log(`My weight is ${this.weight}`);}}const xiaoming = new People('Li Lei', 15, 120);xiaoming.getInfo();
二、JS中常用关系
- 泛化关系
泛化关系其实就是父子类之间的继承关系,表示一般与特殊的关系,指定子类如何特殊化父类的特征和行为。
在UML类图中,用带空心三角箭头的实线来表示泛化关系,箭头从子类指向父类。
- 关联关系
关联关系是对象之间的一种引用关系,表示一个类和另外一个类之间的联系,如老师和学生,丈夫和妻子等。
关联关系有单向和双向的。在UML类图中,单向关联用一个带箭头的实线表示,箭头从使用类指向被关联的类,双向关联用带箭头或者没有箭头的实线来表示。
举例:
class People {constructor(name, house) {this.name = name;this.house = house; // 引用另外一个类}say() {}}class A extends People {constructor(name, house) {super(name, house);}say() {alert('I am A');}}class B extends People {constructor(name, house) {super(name, house);}say() {alert('I am B');}}class House {constructor(city) {this.city = city;}showHouse() {alert(`house is in ${this.city}`);}}let aHouse = new House('杭州');let a = new A('aaa', aHouse);console.log(a); // a 有房子let b = new B('bbb');console.log(b); // b 无房子
上述示例,既有泛化关系,又有关联关系。其UML类图如下:
参考:
