你需要了解的UML类图

首先我们应该先来了解什么是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 {
    // ...
}
关联 - 聚合
  • 整体包含部分,部分可以脱离整体而存在

    例:

关联 - 组合
  • 整体包含部分,部分不可以脱离整体

    例:

关联 - 依赖
  • 不是属性关系,而是函数参数或者返回值

    例:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值