首先我们应该先来了解什么是UML——统一建模语言
统一建模语言是一种为面向对象系统的产品进行说明、可视化和编制文档的一种标准语言,是非专利的第三代建模和规约语言。UML是面向对象设计的建模工具,独立于任何具体程序设计语言。
那么对于设计模式来说,最重要的就是UML类图。下面就让我们一起来学习UML类图吧
UML类图 - 单个类
-
三个区域:名称,属性,方法
-
权限描述:+(public),#(protected),-(private)
例:
class People {
name: string
age: number
protected weight: number = 100
private girlfriend: string = 'xxx'
constructor(name: string, age: number) {
this.name = name
this.age = age
}
eat() {
alert(`${this.name} eat something`)
}
speak() {
alert(`My name is${this.name}, age ${this.age}`)
}
}
UML类图 - 实现
-
实现 - 实现接口
例:
interface IPerson {
name: string
age: number
sayHi(otherName: string): void
}
class Person implements IPerson {
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
sayHi(otherName: string): void {
alert(`Hi,${otherName}`)
}
eat(){
}
speak(){
}
}
UML类图 - 泛化
-
泛化 - 继承父类
例:
class People {
name: string
age: number
protected weight: number = 100
private girlfriend: string = 'xxx'
constructor(name: string, age: number) {
this.name = name
this.age = age
}
eat() {
alert(`${this.name} eat something`)
}
speak() {
alert(`My name is${this.name}`)
}
}
class Student extends People {
school: string
constructor(name: string, age: number, school: string) {
super(name, age)
this.school = school
}
study() {
alert(`${this.name} study`)
}
eat() {
alert(`${this.name} eat apple`)
}
}
class Teacher extends People {
major: string
constructor(name: string, age: number, major: string) {
super(name, age)
this.major = major
}
teach() {
alert(`$${this.name} teach ${this.major}`)
}
}
UML类图 - 关联
-
关联 - A是B的属性
例:
class Employee {
name: string
timeCard: TimeCard
constructor(name: string, timeCard: TimeCard) {
this.name = name
this.timeCard = timeCard
}
}
class TimeCard {
// ...
}
关联 - 聚合
-
整体包含部分,部分可以脱离整体而存在
例:
关联 - 组合
-
整体包含部分,部分不可以脱离整体
例:
关联 - 依赖
-
不是属性关系,而是函数参数或者返回值
例: